I was doing some coding, and I tried to create an instance of TIE without the speed value.
class TIE {
var name: String
var speed: Int
init(name: String, speed: Int) {
self.name = name
self.speed = speed
}
}
let fighter = TIE(name: "wow")
print(fighter.speed)
If the custom initalizer is meant to make sure that no values are Nil, then why can't I just do this?
let fighter = TIE(name: "wow")
print(fighter.speed)
Why do I need to have the speed too? Doesn't this mean that the custom initalizer is useless?
If the custom initalizer is meant to make sure that no values are Nil
That's not quite right... all initializers ("custom" or not) are the code responsible for well, initializing all the properties. Even optionals like Int?
need to be initialized, and in that case nil
is a perfectly valid value you could set.
Why do I need to have the
speed
too?
Because you added a speed
stored property to your TIE
class. If you don't want it, remove it. You can't leave it with an undefined value.
If you want to be able to initialize TIE
objects without setting the speed explicitly, you can use a default argument:
class TIE {
var name: String
var speed: Int
init(name: String, speed: Int = 0) {
self.name = name
self.speed = speed
}
}
print(TIE(name: "This is valid... "))
print(TIE(name: "...and so is this", speed: 123))
If you want to disallow initializing with a custom speed, you can define a static initializer for speed
instead:
class TIE {
var name: String
var speed: Int = 0
init(name: String) {
// speed is already initialized, so you don't need anything like:
// self.speed = 0
self.name = name
}
}
print(TIE(name: "This is valid... "))
print(TIE(name: "...but now this isn't", speed: 123))
// `- error: extra argument 'speed' in call