I'm new to Swift and is trying out the beginner's project of building a calculator. I understand that "display.text" returns an optional string and the string value inside of it has to be unwrapped with "!" before it can be used.
However, I have noticed "display.text" only needs to be unwrapped once and then it can be used multiple times without unwrapping it again. Is this true for Swift optional values? Where could I find some guidelines regarding to the matter?
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypingANumber = false
@IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
display.text = display.text! + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
You should generally avoid to forcibly unwrap optionals (with operator
!
), as this will yield a runtime exception in case the optional containsnil
. Below follows some techniques to handle unwrapping of optionals.Optional binding
Note that the only way you can "unwrap it once and then use it multiple times" if if you unwrap and assign it to another non-optional variable to the same inherent type.
This is what is done when using optional binding:
Nil coalescing operator
If you don't want to explicitly assign the unwrapped value using conditional binding, you can make use of the nil coalescing operator for safe unwrapping.
Now, you could, however, use the nil coalescing operator in a semi-optional-binding fashion; assign the unwrapped value of an optional or some default value if the optional is nil:
Immutable
metaUnwrapped
would be available in its scope, and contain the value ofdisplay.text
(at assignment), if non-nil
, or the default value""
, ifdisplay.text
wasnil
at assignment. You could usemetaUnwrapped
in the same fashion as immutableunwrapped
in the optional binding examples above:Optional chaining
This is slightly off-base w.r.t. your question, but since we're on the subject of optionals and unwrapping, I might as well mention optional chaining.
Optional chaining can be used to access properties of some optional property, given that the optional property is not
nil
. As an example, say you want to count the number of characters in thedisplay.text
, but naturally only if the optional.text
property is non-nil
. In this case, optional chaining combined with the nil coalescing operator could be a proper method of choice: