作者:opheliamaizi | 来源:互联网 | 2024-11-26 14:21
系统: Mac OS 10.15.2, XCode 11.3,swift 5.0
写作时间:2020-01-09
说明
Swift中的闭包(Closure) ,闭包的地位等同于OC中的Block!
Objc 闭包的写法
void (^printBlock)(NSString *x); printBlock = ^(NSString* str) { NSLog(@"print:%@", str); }; printBlock(@"hello world!");
Swift 闭包 的写法
var sumClosure:((a: Int, b: Int) -> Int)sumClosure = { (a: Int, b: Int) -> Int in return a + b}let sum = sumClosure(a: 10,b: 20)print(sum)
Swift 闭包重定义
typealias Myclosure1 = (str:String) ->Void
typealias Myclosure2=(str:String) ->String
typealias Myclosure3=(str:String,str:String)->String
typealias Myclosure4=()->Voidvar closure1: Myclosure1?closure1 = { (str: String) ->Void in print(str)} closure1!(str: "HelloWorld")
Swift 比较作为方法的参数
var closure4:Myclosure4?closure4 = { print("Swift")}func Fun(myclosure: Myclosure4) { myclosure()}Fun(closure4!)
Swift闭包 简化写法
sumClosure = { (a: Int, b: Int) -> Int in return a + b}
sumClosure = { (a,b) -> Int in return a + b}
sumClosure = { (a,b) in return a + b}
sumClosure = { a,b in return a + b}
sumClosure = { return $0 + $1}
returnsumClosure = { $0 + $1}
Swift 闭包常用方式
- 作为非空变量:
var closureName: (ParameterTypes) -> ReturnType
- 作为可为空变量:
var closureName: ((ParameterTypes) -> ReturnType)?
- 作为别名:
typealias ClosureType = (ParameterTypes) -> ReturnType
- 作为静态变量:
let closureName: ClosureType = { ... }
- 作为参数(用别名定义),在函数中:
funcName(parameter: (ParameterTypes) -> ReturnType)
注释: 如果在闭包中的参数会函数体外变化,需要添加修饰词@escaping
.
- 作为函数回调的参数:
funcName({ (ParameterTypes) -> ReturnType in statements })
- 作为函数的参数(不用别名定义):
array.sorted(by: { (item1: Int, item2: Int) -> Bool in return item1 < item2 })
- 作为函数的参数(不用别名定义)&#xff0c;并隐藏参数类型(比如这里的
item1: Int
):
array.sorted(by: { (item1, item2) -> Bool in return item1 < item2 })
- 作为函数的参数(不用别名定义)&#xff0c;并隐藏返回值类型(比如返回值类型为Bool):
array.sorted(by: { (item1, item2) in return item1 < item2 })
- 作为函数的最后一个参数:
array.sorted { (item1, item2) in return item1 < item2 }
- 作为函数的最后一个参数&#xff0c; 省略掉参数声明:
array.sorted { return $0 < $1 }
- 作为函数的最后一个参数&#xff0c; 省略掉返回
return
关键字:
array.sorted { $0 < $1 }
- 作为函数的最后一个参数&#xff0c; 省略掉返回具体实现&#xff0c;只用符号表示比较:
array.sorted(by: <)
- 作为函数的参数&#xff0c;并清楚写清所有参数&#xff0c;返回值&#xff0c;类型&#xff0c;以及实现:
array.sorted(by: { [unowned self] (item1: Int, item2: Int) -> Bool in return item1 < item2 })
- 作为函数的参数&#xff0c;并清楚写清所有参数&#xff0c;返回值&#xff0c;以及实现。其中省略掉参数类型&#xff0c;返回值类型&#xff0c;由上下文推论得出:
array.sorted(by: { [unowned self] in return $0 < $1 })
参考
https://docs.swift.org/swift-book/LanguageGuide/Closures.html
https://www.jianshu.com/p/79ab32f60485
https://fuckingclosuresyntax.com/