检查可选项是否不是nil 几乎总是不必要的。几乎你唯一需要这样做的时候是它的nil-ness 是你想知道的唯一的东西——你不在乎价值是什么,只是它不是 @ 987654325@.
在大多数其他情况下,有一点 Swift 速记可以更安全、更简洁地为您完成 if 内的任务。
如果不是nil,则使用该值
代替:
let s = "1"
let i = Int(s)
if i != nil {
print(i! + 1)
}
你可以使用if let:
if let i = Int(s) {
print(i + 1)
}
你也可以使用var:
if var i = Int(s) {
print(++i) // prints 2
}
但请注意i 将是一个本地 副本 - 对i 的任何更改都不会影响原始可选值中的值。
您可以在单个 if let 中解开多个选项,后面的选项可以依赖于前面的选项:
if let url = NSURL(string: urlString),
data = NSData(contentsOfURL: url),
image = UIImage(data: data)
{
let view = UIImageView(image: image)
// etc.
}
您还可以将where 子句添加到展开的值:
if let url = NSURL(string: urlString) where url.pathExtension == "png",
let data = NSData(contentsOfURL: url), image = UIImage(data: data)
{ etc. }
将nil 替换为默认值
代替:
let j: Int
if i != nil {
j = i
}
else {
j = 0
}
或:
let j = i != nil ? i! : 0
您可以使用 nil-coalescing 运算符 ??:
// j will be the unwrapped value of i,
// or 0 if i is nil
let j = i ?? 0
将可选项与非可选项等同
代替:
if i != nil && i! == 2 {
print("i is two and not nil")
}
您可以检查可选值是否等于非可选值:
if i == 2 {
print("i is two and not nil")
}
这也适用于比较:
if i < 5 { }
nil 始终等于其他nils,并且小于任何非nil 值。
小心!这里可能有陷阱:
let a: Any = "hello"
let b: Any = "goodbye"
if (a as? Double) == (b as? Double) {
print("these will be equal because both nil...")
}
在可选对象上调用方法(或读取属性)
代替:
let j: Int
if i != nil {
j = i.successor()
}
else {
// no reasonable action to take at this point
fatalError("no idea what to do now...")
}
你可以使用可选链,?.:
let j = i?.successor()
请注意,j 现在也是可选的,以解决 fatalError 场景。稍后,您可以使用此答案中的其他技术之一来处理 j 的可选项性,但您通常可以将实际打开选项的时间推迟到很久以后,或者有时根本不进行。
顾名思义,你可以将它们链接起来,所以你可以这样写:
let j = s.toInt()?.successor()?.successor()
可选链也适用于下标:
let dictOfArrays: ["nine": [0,1,2,3,4,5,6,7]]
let sevenOfNine = dictOfArrays["nine"]?[7] // returns {Some 7}
和功能:
let dictOfFuncs: [String:(Int,Int)->Int] = [
"add":(+),
"subtract":(-)
]
dictOfFuncs["add"]?(1,1) // returns {Some 2}
分配给可选属性上的属性
代替:
if splitViewController != nil {
splitViewController!.delegate = self
}
您可以通过分配一个可选链:
splitViewController?.delegate = self
仅当splitViewController 不是nil 时才会发生分配。
如果不是 nil 或 bailing(Swift 2.0 中的新功能),则使用该值
有时在函数中,你想写一小段代码来检查一个可选项,如果是nil,请提前退出函数,否则继续。
你可以这样写:
func f(s: String) {
let i = Int(s)
if i == nil { fatalError("Input must be a number") }
print(i! + 1)
}
或避免强制展开,如下所示:
func f(s: String) {
if let i = Int(s) {
print(i! + 1)
}
else {
fatalErrr("Input must be a number")
}
}
但最好将错误处理代码保留在检查的顶部。这也可能导致令人不快的嵌套(“厄运金字塔”)。
您可以改为使用guard,类似于if not let:
func f(s: String) {
guard let i = Int(s)
else { fatalError("Input must be a number") }
// i will be an non-optional Int
print(i+1)
}
else 部分必须退出受保护值的范围,例如return 或 fatalError,以保证受保护的值在范围的其余部分有效。
guard 不限于函数范围。例如:
var a = ["0","1","foo","2"]
while !a.isEmpty {
guard let i = Int(a.removeLast())
else { continue }
print(i+1, appendNewline: false)
}
打印321。
循环遍历序列中的非零项(Swift 2.0 中的新功能)
如果你有一系列可选元素,你可以使用for case let _? 来遍历所有非可选元素:
let a = ["0","1","foo","2"]
for case let i? in a.map({ Int($0)}) {
print(i+1, appendNewline: false)
}
打印321。这是使用可选的模式匹配语法,它是一个变量名,后跟?。
您也可以在switch 语句中使用此模式匹配:
func add(i: Int?, _ j: Int?) -> Int? {
switch (i,j) {
case (nil,nil), (_?,nil), (nil,_?):
return nil
case let (x?,y?):
return x + y
}
}
add(1,2) // 3
add(nil, 1) // nil
循环直到函数返回nil
很像if let,你也可以写while let并循环直到nil:
while let line = readLine() {
print(line)
}
您也可以写while var(与if var 类似的注意事项适用)。
where 子句也可以在这里工作(并终止循环,而不是跳过):
while let line = readLine()
where !line.isEmpty {
print(line)
}
将可选参数传递给一个接受非可选参数并返回结果的函数
代替:
let j: Int
if i != nil {
j = abs(i!)
}
else {
// no reasonable action to take at this point
fatalError("no idea what to do now...")
}
您可以使用可选的map 运算符:
let j = i.map { abs($0) }
这与可选链接非常相似,但是当您需要将非可选值作为参数传递给函数到时。与可选链接一样,结果将是可选的。
当你想要一个可选的时候,这很好。例如,reduce1 类似于 reduce,但使用第一个值作为种子,如果数组为空,则返回一个可选值。你可以这样写(使用前面的guard 关键字):
extension Array {
func reduce1(combine: (T,T)->T)->T? {
guard let head = self.first
else { return nil }
return dropFirst(self).reduce(head, combine: combine)
}
}
[1,2,3].reduce1(+) // returns 6
但您可以改为 map .first 属性,然后返回:
extension Array {
func reduce1(combine: (T,T)->T)->T? {
return self.first.map {
dropFirst(self).reduce($0, combine: combine)
}
}
}
将可选项传递给接受可选项并返回结果的函数,避免烦人的双重可选项
有时,您想要类似于map 的东西,但是您想要调用的函数本身 返回一个可选值。例如:
// an array of arrays
let arr = [[1,2,3],[4,5,6]]
// .first returns an optional of the first element of the array
// (optional because the array could be empty, in which case it's nil)
let fst = arr.first // fst is now [Int]?, an optional array of ints
// now, if we want to find the index of the value 2, we could use map and find
let idx = fst.map { find($0, 2) }
但现在idx 是Int?? 类型,是双重可选的。相反,您可以使用flatMap,它将结果“扁平化”为单个可选:
let idx = fst.flatMap { find($0, 2) }
// idx will be of type Int?
// and not Int?? unlike if `map` was used