快速关闭,关闭签名和关闭等效

时间:2018-09-22 08:51:10

标签: swift xcode

我很好奇为什么此闭包分配在Swift 4.1中有效(尚未在Swift 4.2中进行测试,但是两个代码片段在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)")
        }
    })
}

但是,这不是:

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

还是在4.1编译器中只是一个错误?

1 个答案:

答案 0 :(得分:1)

观察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

可行是因为t2t4将采用Int个参数,这些参数与Any和{中的t1 {1}},但是如果您采取相反的操作,则不会因为t3无法接受Int值。


观察2

现在,闭包再次收到一个参数。因此,如果将Any参数传递给Int是有效的,但是如果将Any传递给Any,则无效。

因此,此不起作用

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,反之亦然。