I was doing one of the tests in 100 days of Swift UI, and I tried running this code in the playground. I was wondering, what is the point of the custom initializer in lines 4-7?
Why do I need these lines in a class? Why won't the code work if I delete these lines? I still provided all of the variables needed.
class TIE {
var name: String
var speed: Int
init(name: String, speed: Int) {
self.name = name
self.speed = speed
}
}
let fighter = TIE(name: "wow", speed: 50)
let interceptor = TIE(name: "cool", speed: 70)
If I try to delete the custom initializer, the code breaks. Why?
I was doing one of the tests in 100 days of Swift UI, and I tried running this code in the playground. I was wondering, what is the point of the custom initializer in lines 4-7?
Why do I need these lines in a class? Why won't the code work if I delete these lines? I still provided all of the variables needed.
class TIE {
var name: String
var speed: Int
init(name: String, speed: Int) {
self.name = name
self.speed = speed
}
}
let fighter = TIE(name: "wow", speed: 50)
let interceptor = TIE(name: "cool", speed: 70)
If I try to delete the custom initializer, the code breaks. Why?
Share Improve this question edited Feb 6 at 19:27 TylerH 21.1k77 gold badges79 silver badges112 bronze badges asked Feb 5 at 16:38 Brody KavanaghBrody Kavanagh 391 silver badge8 bronze badges 3
name
andspeed
can not benil
. So you need to have an initialization that will give them values. If you dovar fighter = TIE()
, nothing say that you would give really a value toname
andspeed
afterwards. Hence the initialization needed. – Larme Commented Feb 5 at 16:43