Chapter 15, Bronze Challenge Solution

To solve the Bronze Challenge, I modified my Town.swift structure:

import Foundation

struct Town {
    var population = 5_422
    var numberOfStoplights = 4
    
    func printDescription() {
        print("Populations: \(population); number of stoplights: \(numberOfStoplights)")
    }
    
    mutating func changePopulation(by amount: Int) {
        if population + amount > 0 {
            population += amount
        } else {
            population = 0
        }
    }
}

Is there a more elegant way to write the changePopulation(by:) method?

There’s a couple other ways you could write it but they all basically do the same thing. The most concise would be

mutating func changePopulation(by amount: Int) {
    population = max(population+amount, 0)
}
1 Like