深入讲解Swift中的模式匹配

2020-01-09 00:19:03王旭


for case let val? in values {
 print("Value in values is (val)")
}

或者:


valuesIterator = values.makeIterator()
while let val = valuesIterator.next(), val != nil {
 print("Value in values is (String(describing: val))")
}

这样就可以将 nil 值给过滤了,是不是很简单?还可以使用 for case 匹配枚举值数组:


let results: [Result] = [.success, .failure]
for case .success in results {
 print("Values in results contains success.")
 break
}

对于复杂的枚举类型:


enum NetResource {
 case http(resource: String)
 case ftp(resource: String)
}

let nets: [NetResource] = [.http(resource: "https://www.easck.com//www.apple.cn"), .ftp(resource: ftp://192.0.0.1)]

过滤 http 的值:


for case .http(let resource) in nets {
 print("HTTP resource (resource)")
}

for 循环使用 where 从句

除此之外,我们还可以在 for 循环后边跟上一个 where 从句来进行模式匹配:


for notNilValue in values where notNilValue != nil {
 print("Not nil value: (String(describing: notNilValue!))")
}

查询一个数组里边所有能被3整除的数:


let rangeValues = Array(0...999)
for threeDivideValue in rangeValues where threeDivideValue % 3 == 0 {
 print("Three devide value: (threeDivideValue)")
}

查询所有含有3的数:


for containsThree in rangeValues where String(containsThree).contains("3") {
 print("Value contains three: (containsThree)")
}