0
我有一個與指數遍歷記住,像這樣的數組實例的擴展:斯威夫特陣列關閉擴展引發錯誤
extension Array {
func fun (_ iterator: (Int, Element) -> Void) -> Void {
for (key,value) in self.enumerated() {
iterator(key,value)
}
}
}
現在,我想稱之爲:
[.leading,.trailing,.bottom,.top].fun {
(index, element) in
var c : Int = index % 2 == 0 ? 20 : -20 // THAT LINE
NSLayoutConstraint(item: subView, attribute: element, relatedBy: .equal, toItem: self.view, attribute: element , multiplier: 1, constant: c).isActive = true
}
然而這會產生一個錯誤:表達式的類型在沒有更多上下文的情況下是不明確的。 當我刪除該行(片段中的「THAT LINE」) - 它可以工作。當我添加這個或任何其他代碼,甚至一些變量聲明 - 它給了我同樣的例外。
出現該錯誤僅在Xcode,在終端工作原理:
swift
Welcome to Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1). Type :help for assistance.
1>
2>
3> extension Array {
4. func fun (_ iterator: (Int, Element) -> Void) -> Void {
5. for (key,value) in self.enumerated() {
6. iterator(key,value)
7. }
8. }
9. }
10> [0,1,2,3,4].fun {
11. (index, element) in
12.
13. var c : Int = index % 2 == 0 ? 20 : -20 // THAT LINE
14. print(c)
15. }
20
-20
20
-20
20
我相信這可能是由於已知的錯誤([SR-1570](https://bugs.swift.org/browse/SR-1570)),Swift無法推斷出閉包的參數類型當在沒有外部上下文的多語句閉包中調用'fun'時)。如果你明確提供參數類型,你的例子應該編譯。當您刪除「該行」時,提供的閉包不再是多語句閉包。但請注意,你的第二個例子適合我編譯。 – dfri
謝謝dfri,這是什麼導致它(全參數類型推理) –