Swift 将代码更优雅 —— 控制流


if let 可选绑定

var optionalName : String? = "Cone"
var greet = "hello!"
if let name = optionalName {
   greet = "Hello, \(name)"
}
print(greet)
// Hello, Cone

这段代码如何运行呢?如果变量的可选值为nil,条件会判断为false,大括号中的代码会跳过,如果不是nil,会将值赋给let后面的常量,这样代码快中就可以使用这个值了。

switch

let vegetable = "red pepper"
switch vegetable {
case "celery":
    let comment = "celery";
    print(comment)
case "cucumber", "watercress":
    let comment = "cucumber, watercress";
    print(comment)
case let x where x.hasSuffix("pepper"):
    let comment = "It is a \(x)";
    print(comment)
default:
    let comment = "nothing";
    print(comment)
}
// It is a red pepper

Swift中的switch语句支持很多种情况,包括枚举、范围、元组等等。

where

where关键字在Swift中非常强大,谈谈使用场景。

与switch 做限定使用
let name = ["王二","张三","李四","王五"]
name.forEach { 
    switch $0 {
    case let x where x.hasPrefix("王"):           print("\(x)是笔者本家")
    default: print("你好,\($0)")
} }

// 输出:
// 王二是笔者本家
// 你好,张三
// 你好,李四
// 王五是笔者本家
在 for中做限定
let num: [Int?] = [48, 99, nil]
    let n = num.flatMap {$0}
for score in n where score > 60 {
    print("及格啦 - \(score)")
}
// 输出:
// 及格啦 - Optional(99)        
对协议扩展做条件限制
extension Sequence where Self.Iterator.Element : Comparable {
public func sorted() ->[Self.Iterator.Element]
}
    

文章作者: Cone
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 Cone !
  目录