代碼的結果是:
NUM1是可選的(5)
NUM2是可選的(5)
NUM2是5
我想知道爲什麼,如果{} NUM2是一個可選值,但打印 「NUM2 5」在迅速累積打印可選值,當非可選
var optionalNum : Int? = 5
let num1 = optionalNum
print("num1 is \(num1)")
if let num2 = optionalNum {
print("num2 is \(optionalNum)")
print("num2 is \(num2)")
} else {
print("optionalNum does not hold a value")
}
的原因,因爲在這一行'如果讓NUM2 = {optionalNum'你剛纔_unwrapped_'optionalNum'成'num2',這是不是一個可選的了。 – holex
我強烈建議閱讀[Swift編程語言指南的Optionals部分](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/ uid/TP40014097-CH5-ID330)(特別是可選綁定) – Hamish
還有一個關於此主題的出色SO文檔頁面,http://stackoverflow.com/documentation/swift/475/conditionals/1560/optional-binding-and- where-clause#t = 201611091355361786641 – milo526