Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare but not initialize a property in a Swift class

Tags:

swift

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.

like image 978
user3288177 Avatar asked Dec 15 '22 07:12

user3288177


2 Answers

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 image 51
Blake Lockley Avatar answered Mar 08 '23 09:03

Blake Lockley


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.

like image 40
MikeG Avatar answered Mar 08 '23 09:03

MikeG