I am retyping the code & recreating the files in the project as I am going through this chapter (mostly as I have been making my own deviations, comments, etc, as I go through each chapter, so it often no longer looks like the syntax in the book).
In this chapter, I started recreating the Town struct, including the new init() initializers.
Now I am into the section that amends the Monster class(es). However, after retyping the code, I now get a bunch of compile errors around “var town = Town?” and its all to do with the above new initializers I have created.
Here is my code:
Town.swift
import Foundation
struct Town {
var population: Int {
didSet(oldPop) {
print(“Pop changed to (population) from (oldPop)”)
}
}
var noStopLights: Int
let region: Stringenum Size{ } // Methods init(region: String, population: Int, stopLights: Int) { self.region = region self.population = population noStopLights = stopLights } init(population: Int, stopLights: Int) { self.init(region: "N/A", population: population, stopLights: stopLights) } func printDescription() { print("Population: \(population). No of Stop Lights: \(noStopLights). Region: \(region)") } mutating func changePop(by amount: Int) { population += amount }
}
Monster.swift
import Foundation
class Monster {
var town = Town?()
var name: String
var victimPool: Int {
get {
return town?.population ?? 0
}
set(newVictimPool) {
town?.population = newVictimPool
}
}// Methods init(town: Town?, monsterName: String) { self.town = town name = monsterName } func terroriseTown() { if town != nil { print("\(name) is terrorising the town") } else { print("\(name) has found a town to terrorise") } }
}
main.swift
import Foundation
// Memberwise Initializers ONLY work on struct’s
var firstTown = Town(region: “NE”, population: 10_000, stopLights: 10)
firstTown.printDescription()// Manual init functions defined. This 1 only has 2 of 3 properties. 3rd is defaulted in the code
var secondTown = Town(population: 1_000, stopLights: 5)
secondTown.printDescription()
How can I resolve this? Why isn’t the same happening in the book?
From XCode’s tool tips suggestion, if I put “var town = Town?()” most other compile errors disappear, but a compile error remains on this line (only), stating “Cannot invoke initializer for type ‘Town?’ with no arguments”