[英]Swift completion block
我很難理解我遇到的問題。 為簡化起見,我將使用UIView方法。 基本上,如果我寫的方法
UIView.animateWithDuration(1, animations: {() in
}, completion:{(Bool) in
println("test")
})
它工作正常。 現在,如果我使用相同的方法,但創建一個這樣的字符串:
UIView.animateWithDuration(1, animations: {() in
}, completion:{(Bool) in
String(23)
})
它停止工作。 編譯器錯誤: 在調用中缺少參數'delay'的參數
現在,這是奇怪的部分。 如果我執行與失敗的代碼完全相同的代碼,但只需添加如下的打印命令:
UIView.animateWithDuration(1, animations: {() in
}, completion:{(Bool) in
String(23)
println("test")
})
它又開始起作用了。
我的問題基本上是一回事。 我的代碼:
downloadImage(filePath, url: url) { () -> Void in
self.delegate?.imageDownloader(self, posterPath: posterPath)
}
不行。 但如果我換到。
downloadImage(filePath, url: url) { () -> Void in
self.delegate?.imageDownloader(self, posterPath: posterPath)
println("test")
}
甚至:
downloadImage(filePath, url: url) { () -> Void in
self.delegate?.imageDownloader(self, posterPath: posterPath)
self.delegate?.imageDownloader(self, posterPath: posterPath)
}
它工作正常。 我不明白為什么會這樣。 我接近它接受它是一個編譯器錯誤。
當Swift僅由單個表達式組成時,它們具有隱式返回 。 這允許簡潔的代碼,例如:
reversed = sorted(names, { s1, s2 in s1 > s2 } )
在您的情況下,當您在此處創建字符串時:
UIView.animateWithDuration(1, animations: {() in }, completion:{(Bool) in
String(23)
})
你最終返回該字符串,這使得你的閉包簽名:
(Bool) -> String
這不再匹配animateWithDuration
的簽名所需的animateWithDuration
(這Missing argument for parameter 'delay' in call
錯誤中轉換為Swift Missing argument for parameter 'delay' in call
的神秘Missing argument for parameter 'delay' in call
因為它無法找到匹配的適當簽名)。
一個簡單的解決方法是在閉包結束時添加一個空的return語句:
UIView.animateWithDuration(1, animations: {() in}, completion:{(Bool) in
String(23)
return
})
這使你的簽名應該是什么:
(Bool) -> ()
你最后一個例子:
downloadImage(filePath, url: url) { () -> Void in
self.delegate?.imageDownloader(self, posterPath: posterPath)
self.delegate?.imageDownloader(self, posterPath: posterPath)
}
因為那里有兩個表達式,而不僅僅是一個表達式; 隱式返回僅在閉包包含單個表達式時發生。 因此,該閉包不返回任何東西,並且與其簽名相匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.