關于Optional的Control Flow
if let constantName = someOptional { statements }
如果該Optional為nil,則不進入if,否則執行且constantName為該Optional的值
例子:
if let actualNumber = possibleNumber.toInt() { PRintln("/(possibleNumber) has an integer value of /(actualNumber)") } else { println("/(possibleNumber) could not be converted to an integer") }
關于nil
optional可以被賦值為nil
例如:
var serverResponseCode: Int? = 404 serverResponseCode = nil var surveyAnswer: String? // surveyAnswer is automatically set to nil
optional的拓展:Implicitly Unwrapped Optionals
有的時候,一個optional在第一次賦值之后將是安全的,不用做nil檢查
定義:String! 而不是 String?
舉例:
let possibleString: String? = "An optional string." println(possibleString!) // requires an exclamation mark to access this value // prints "An optional string." let assumedString: String! = "An implicitly unwrapped optional string." println(assumedString) // no exclamation mark is needed to access its value // prints "An implicitly unwrapped optional string."
對于這種特殊類型(IUO),適用普通optional用法:
if assumedString {println(assumedString)}
|
新聞熱點
疑難解答