swift中block
Swift中的闭包(closure)是一种可以在代码中传递和引用的功能强大的代码块。闭包类似于函数,但是没有名称和参数名称,它们可以捕获和存储其所在上下文的任何常量和变量的引用。
闭包有三种形式:全局函数、嵌套函数和闭包表达式。闭包表达式是一种轻量级的语法,它可以在代码中内联定义和使用闭包。
闭包表达式的语法如下:
{ (parameters) -> return type in
statements
}
其中,参数和返回值类型都可以省略,闭包可以没有参数、没有返回值或者两者都没有。
闭包可以用在许多地方,例如:
- 传递函数作为参数:
func operateOnNumbers(_ a: Int, _ b: Int, operation: (Int, Int) -> Int) -> Int {
return operation(a, b)
}
let add = { (a: Int, b: Int) -> Int in
return a + b
}
let result = operateOnNumbers(5, 3, operation: add)
print(result)
- 作为函数的返回值:
func makeAdder(_ x: Int) -> ((Int) -> Int) {
return { (y: Int) -> Int in
return x + y
}
}
let add5 = makeAdder(5)
let sum = add5(3)
print(sum)
- 用于排序:
let names = ["Tom", "Jerry", "Spike", "Tyke"]
let sortedNames = names.sorted { (a: String, b: String) -> Bool in
return a < b
}
print(sortedNames)
- 用于异步操作:
func fetchData(completion: (Result<Data, Error>) -> Void) {
// fetch data asynchronously
// ...
completion(.success(data))
}
fetchData { (result) in
switch result {
case .success(let data):
print(data)
case .failure(let error):
print(error.localizedDescription)
}
}
``
原文地址: http://www.cveoy.top/t/topic/huC6 著作权归作者所有。请勿转载和采集!