2

I am new to iOS development. I am doing this project by watching video tutorial, where they are using the earlier version of Swift, but I am using Swift.

I came across to this problem. Two optional integers are unwrapped when being used for calculation. But it is not unwrapped when the text is given to the label.

I tried to unwrap them again when the text is given to the label and it worked. Why it is behaving strange?

var leftNumber: Int!
var rightNumber: Int!

func generateProblem() {
    leftNumber = generateRandomNumber()
    rightNumber = generateRandomNumber()

    // The problem is here
    problemLabel.text = "\(leftNumber) x \(rightNumber)"
}

func generateRandomNumber() -> Int {
    return Int(arc4random_uniform(UInt32(9))) + 1
}

The screenshot of simulator:

screen

Wide Angle Technology
  • 1,184
  • 1
  • 8
  • 28
Marat
  • 6,142
  • 6
  • 39
  • 67

1 Answers1

2

In Swift 3, an implicitly-unwrapped optional is the same as an optional, except that it will implicitly unwrap in contexts that require it. For instance, if you had a func foo(i: Int), you could write foo(i: leftNumber) and the compiler would perform the unwrap operation for you.

String interpolation is not a context where unwrapping is required. As you can use an optional there, Swift prefers the optional case and does not unwrap for you.

Tutorials that you find online may either not have been updated for Swift 3, or there may have been a misunderstanding.

zneak
  • 134,922
  • 42
  • 253
  • 328
  • So it means that implicit unwrapping is now in the past? Should I always use `?` instead of `!` and not worry about will the compiler unwrap or not? – Marat Sep 21 '16 at 04:08
  • To be clear, you should default to not wrapping whenever possible. Implicit unwrapping is mostly useful when, for a reason or another, you know that a variable will always have a value but can't prove it to the compiler, and in that case it will still help you get rid of some boilerplate. Explicit wrapping is still useful in a myriad of cases. – zneak Sep 21 '16 at 04:11
  • Ok! Thank you @zneak I appreciate your help – Marat Sep 21 '16 at 04:12