swift - Swift closures, closure signatures, and closure equivalence
问题描述
I'm kind of curious why this closure assignment works in Swift 4.1 (not tested yet under Swift 4.2, but both snippets don't work in Swift <= 4.0):
func intArrayFunc(_ policy: Int = 0, completion: (([Int]?, Error?) -> Void)? = nil) {
print("policy = '\(policy)'")
completion?([policy + 2], nil)
}
typealias anyArrayClosure = (Int, (([Any]?, Error?) -> Void)?) -> Void
let a: anyArrayClosure = intArrayFunc(_:completion:)
a(1) { (results, error) in
results?.forEach({ (result) in
if let oneResult = result as? Int {
print("\(oneResult) (Should be 3)")
}
})
}
However, this doesn't:
func t1(_ int: Int = 0, array: [Any]? = nil) {
print("t1")
}
func t3(_ int: Int = 0, array: [Int]? = nil) {
print("t3")
}
typealias function = (Int, [Any]?) -> Void
let t2: function = t1
let t4: function = t3
Or is it a just a bug in the 4.1 compiler?
解决方案
观察 1
func t1(_ int: Int = 0, array: [Any]? = nil, completion: ((Int) -> ())) {
print("t1")
}
func t3(_ int: Int = 0, array: [Any]? = nil, completion: ((Int) -> ())) {
print("t3")
}
typealias function = (Int, [Int]?, ((Any) -> ())) -> Void
let t2: function = t1
let t4: function = t3
这是有效的,因为t2
andt4
将采用与in和Int
兼容的参数,但如果你做相反的事情,它不会因为,不能接受一个值。Any
t1
t3
Int
Any
观察 2
现在闭包再次收到一个参数。因此,如果将Int
参数传递给Any
它是有效的,但如果你传递Any
给 an Int
,则不是。
所以,这行不通。
func t1(_ int: Int = 0, array: [Any]? = nil, completion: ((Int) -> ())) {
print("t1")
}
func t3(_ int: Int = 0, array: [Any]? = nil, completion: ((Any) -> ())) {
print("t3")
}
typealias function = (Int, [Int]?, ((Int) -> ())) -> Void
let t2: function = t1
let t4: function = t3
因此,最终归结为一个简单的事实,即您传递给变量的任何内容都应该与其类型兼容。您可以传递和传递,Int
但Any
反之亦然。
推荐阅读
- c++ - 在 C++ 中从文件读取并动态分配到 Student 类型的数组中
- javascript - 用 Jest 发出警告
- mapbox - mapbox 表达式通过 id 数组过滤图层的特征属性(特征 id)
- html - 我的链接属性在 html 和 css 工作表之间不起作用
- elasticsearch - Elasticseach 使用 NEST 将索引替换为新的但别名相同的索引
- react-native - react-native flatList 是灰色的
- asp.net - 在访问说明符上使用 Rest Web API 执行 CRUD 操作时出错
- oracle - 更新以特殊字符开头的 oracle 记录
- firebase - 火力基地。如何使用 URL 执行功能并加载网页(托管)
- java - Java - 在 Super 之前设置类属性