Swift泛型和闭包的结合使用(Generic Closure)

1
2
3
4
5
6
7
typealias Closure = (Any?) -> ()

var closure: Closure?

func closure(closure: @escaping closure) {
self. closure = closure
}

通常我们会用如上方式使用闭包,但是最后会导致工程里面的typealias满天飞,这时候我们会想,有没有办法把这部分代码抽取出来一劳永逸呢?这时候,泛型就派上用场了。

我们对上面的闭包类型作如下定义:

1
public typealias Closure<T> = (T) -> ()

然后在需要用到闭包的地方添加该类型的属性和对应的回调方法即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var btn1Cls: Closure<String>?
var btn2Cls: Closure<(msg: String, code: Int, person: Person)>?
var voidCls: Closure<()>?

func btn1Cls(btn1Cls: @escaping Closure<String>) {
self.btn1Cls = btn1Cls
}

func btn2Cls(btn2Cls: @escaping Closure<(msg: String, code: Int, person: Person)>) {
self.btn2Cls = btn2Cls
}

func voidCls(voidCls: @escaping Closure<()>) {
self.voidCls = voidCls
}

详细代码见:GenericClosure

您的支持将鼓励我继续创作!
0%