标签:
关于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”)
}
// prints “123 has an integer value of 123”
关于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)
}
Assertions – debugging中发现问题后的中断
let age = –3
assert(age >= 0, “A person’s age cannot be less than zero”)
// assertion trigger
标签:
原文地址:http://www.cnblogs.com/zhjch/p/4241353.html