I wonder if someone can explain it to me. For example, on the page 188, there is init code that adds a member wise initializer. I completely omitted the code and just wrote var myTown = Town (Region: "East", population: 10000, Stoplights: 12 )
in the main.swift and no errors popped up. Can someone explain why exactly do I need to use that init code? Thanks
A struct comes with a default memberwise initialiser. Therefore, provide an initialiser only when the default initialiser won’t do the job.
// With default initialiser
struct FooBar {
let jibber: Bool
let jabber: Int
}
// With explicit initialiser
struct FooBar2 {
let jibber: Bool
let jabber: Int
init (jibber:Bool, jabber:Int) {
self.jibber = jibber
self.jabber = 17 * jabber
}
}
let fooBar = FooBar (jibber:true, jabber:9)
let fooBar2 = FooBar2 (jibber:true, jabber:9)
print (fooBar)
print (fooBar2)
For more information, read Default Initializers in The Swift Programming Language (Swift 3.0.1).