几乎总是没有必要检查可选选项是否不存在nil
。几乎唯一需要执行此操作的时间是nil
-ness 是only你想知道的事情——你不关心它的值是什么,只是它不是nil
.
在大多数其他情况下,有一些 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
将是一个local复制 - 任何更改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
}
or:
let j = i != nil ? i! : 0
您可以使用零合并运算符,??
:
// 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
总是等于其他nil
s,并且小于任何非nil
value.
当心!这里可能存在问题:
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()
Note, 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
}
你可以分配through可选链:
splitViewController?.delegate = self
Only if splitViewController
is non-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)
}
The else
part must退出保护值的范围,例如Areturn
or fatalError
,以保证受保护的值对于范围的其余部分有效。
guard
不限于功能范围。例如以下内容:
var a = ["0","1","foo","2"]
while !a.isEmpty {
guard let i = Int(a.removeLast())
else { continue }
print(i+1, appendNewline: false)
}
prints 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)
}
prints 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
apply).
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) }
这与可选链接非常相似,但是当您需要传递非可选值时into函数作为参数。与可选链一样,结果是可选的。
当你想要一个可选的东西时,这很好。例如,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
the .first
属性,并返回:
extension Array {
func reduce1(combine: (T,T)->T)->T? {
return self.first.map {
dropFirst(self).reduce($0, combine: combine)
}
}
}
将可选值传递给接受可选值并返回结果的函数,避免烦人的双可选值
有时,您想要类似的东西map
,但是你要调用的函数itself返回一个可选的。例如:
// 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) }
But now idx
属于类型Int??
,双选。相反,您可以使用flatMap
,它将结果“扁平化”为单个可选值:
let idx = fst.flatMap { find($0, 2) }
// idx will be of type Int?
// and not Int?? unlike if `map` was used