Am getting this issue with this struct, on the line which reads "lazy var townSize: Size ={" and can't figure out what the issue is.
struct Town {
let region = "South"
var population = 5422
var numberOfStoplights = 4
enum Size {
case Small
case Medium
case Large
}
lazy var townSize: Size = {
switch self.population {
case 0...10000:
return Size.Small
case 10001...100000:
return Size.Medium
default:
return Size.Large
}
}
func printTownDescription() {
print("Population: \(myTown.population), number of stoplights: \(myTown.numberOfStoplights)")
}
mutating func changePopulation(amount: Int) {
population += amount
}
}
As has been noted, to initialize a stored property with a closure, you need the ()
after that closing brace:
lazy var townSize: Size = {
switch self.population {
case 0 ... 10000:
return .Small
case 10001 ... 100000:
return .Medium
default:
return .Large
}
}()
But, because population
is a variable, not a constant, you don't want townSize
to be a stored property at all. Instead, you want it to be a computed property, to accurately reflect any changes in the population
:
var townSize: Size {
switch population {
case 0 ... 10000:
return .Small
case 10001 ... 100000:
return .Medium
default:
return .Large
}
}
Note the lack of the =
.
If you use a lazy
stored property, if population
changes subsequent to accessing townSize
, the townSize
won't reflect this accordingly. But using a computed property solves this problem.
You incorrectly declared lazy var it should be declared like this
lazy var townSize: Size = {
switch self.population {
case 0...10000:
return Size.Small
case 10001...100000:
return Size.Medium
default:
return Size.Large
}
}()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With