class car {
var oneWheel : Wheel
func run(inputWheel:Wheel){
oneWheel = inputWheel
....
}
}
I don't want to implement init() and I don't want to initialize the wheel.
Create an implicitly unwrapped optional - this will act like a normal variable but it does not need to be initialised - its initial value is nil
. Just ensure the value is set before it is used otherwise you will get a fatal error for unwrapping nil.
class car {
var oneWheel: Wheel!
func run(inputWheel: Wheel) {
wheel = inputWheel
}
}
Like so...
class car {
var oneWheel : Wheel?
// with this version, in order to pass oneWheel into this function as an argument, you will need to unwrap the optional value first. (see below example)
func run(inputWheel:Wheel){
oneWheel = inputWheel
....
}
}
or if you would like the function to take an optional type Wheel
as an argument do
class car {
var oneWheel : Wheel?
func run(inputWheel:Wheel?){
//use conditional binding to safely unwrap the optional
if let wheel = inputWheel {
oneWheel = wheel
}
....
}
}
By using conditional binding, instead of an implicitly unwrapped optional, you avoid the potential of crashing due to... unexpectedly found nil while unwrapping an optional value
, which occurs when the compiler finds nil where a non-nil value was expected.
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