关于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)}
新闻热点
疑难解答