Marat Marat - 1 year ago 105
Swift Question

Swift 3: Cannot automatically unwrap optional before setting it to Label

I'm new to iOS development. I have doing project by watching video tutorial where author is using earlier version of Swift. Mine is Swift 3 and Xcode 8.

I came across to this problem. Two optional integers are unwrapped while being used for calculation in the rest of code but not unwrapped when setting text to label with them.

I have tried to unwrap them again when setting text 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:


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download