Swift 闭包速查

  • 内容
  • 评论
  • 相关

基础语法

  { (parameters) -> (return type) in
    statements
  }

//闭包的函数整体部分由关键字 in 导入,这个关键字表示闭包的形式参数类型和返回类型定义已经完成,并且闭包的函数体即将开始。

reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
    return s1 > s2
})

自动推测类型(省略参数)

reversedNames = names.sorted(by: { s1, s2 in
           return s1 > s2
} )

隐式返回

reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )

简写参数

reversedNames = names.sorted(by: { $0 > $1 } )
//$0 = s1,$1 = s2

尾随闭包

reversedNames = names.sorted() { $0 > $1 }
//只有唯一参数时可以省略括号
reversedNames = names.sorted{ $0 > $1 }

let strings = numbers.map { (number) -> String in
    var number = number
    var output = ""
    repeat {
        output = digitNames[number % 10]! + output
        number /= 10
    } while number > 0
    return output
}

func loadPicture(from server: Server, completion: (Picture) -> Void, onFailure: () -> Void) {
    if let picture = download("photo.jpg", from: server) {
        completion(picture)
    } else {
        onFailure()
    }
}

loadPicture(from: someServer) { picture in
    someView.currentPicture = picture
} onFailure: {
    print("Couldn't download the next picture.")
}

loadPicture(from: someServer) { picture in
    someView.currentPicture = picture
} onFailure: {
    print("Couldn't download the next picture.")
}

更多参考https://www.cnswift.org/closures

评论

0条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注