4
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.

3
  • 1
    Declare it as optional, var oneWheel: Wheel? Commented Mar 18, 2016 at 3:13
  • Why don't you want to implement init? Are you anti-init? Commented Mar 18, 2016 at 4:06
  • Because I don't like a init(){} dangling in a class and does nothing. Commented Mar 18, 2016 at 16:25

2 Answers 2

9

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
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works. But for someone who is clearly new to optionals, recommending that they use implicitly unwrapped optionals is sending them down a painful path of unexpectedly found nil while unwrapping an optional value
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.