这个问题很大程度上基于这个问题:
主要区别在于我也想将参数传递给闭包.说我有这样的事情:
func someFunctionThatTakesAClosure(completionClosure: (venues: Dictionary<String, AnyObject>, error: NSError) -> ()) {
// function body goes here
var error: NSError?
let responseDictionary: Dictionary<String, AnyObject> = ["test" : "test2"]
completionClosure(venues: responseDictionary, error: error!)
}
Run Code Online (Sandbox Code Playgroud)
这里没有错误.但是当我在主视图控制器中调用此函数时,我尝试了几种方法,但所有结果都会导致不同的错误:
venueService.someFunctionThatTakesAClosure(completionClosure(venues: Dictionary<String, AnyObject>, error: NSError){
})
Run Code Online (Sandbox Code Playgroud)
或者像这样:
venueService.someFunctionThatTakesAClosure((venues: Dictionary<String, AnyObject>, error: NSError){
})
Run Code Online (Sandbox Code Playgroud)
或者甚至喜欢这样:
venueService.someFunctionThatTakesAClosure(completionClosure: (venues: Dictionary<String, AnyObject>, error: NSError) -> (){
});
Run Code Online (Sandbox Code Playgroud)
我可能只是累了,但任何帮助都会非常感激!
venueService.someFunctionThatTakesAClosure({
venues, error in
// do stuff
})
Run Code Online (Sandbox Code Playgroud)
您可以选择指定类型(但由于编译器知道闭包应该提供什么类型,因此您不必严格要求:
venueService.someFunctionThatTakesAClosure({
(venues: Dictionary<String, AnyObject>, error: NSError) -> () in
// do stuff
})
Run Code Online (Sandbox Code Playgroud)
但是我在你的调用代码中看到另一个问题:
completionClosure(venues: responseDictionary, error: error!)
// No Bueno. What if there's no error? ^^^^^^
Run Code Online (Sandbox Code Playgroud)
你不应该强行打开错误,因为它完全有可能它仍然是零.强制展开nil会导致错误.所以你想要这个:
completionClosure(venues: responseDictionary, error: error)
Run Code Online (Sandbox Code Playgroud)
并且您想要更改闭包以获取可选错误.总共:
func someFunctionThatTakesAClosure(completionClosure: (venues: Dictionary<String, AnyObject>, error: NSError?) -> ()) {
…
completionClosure(venues: responseDictionary, error: error)
}
// when calling:
venueService.someFunctionThatTakesAClosure({
(venues: Dictionary<String, AnyObject>, error: NSError?) -> () in
// do stuff
})
Run Code Online (Sandbox Code Playgroud)
如果你想传递额外的参数,请记住swift是针对作为最后一个参数传递的闭包进行优化的(并且它是objective-c API中广泛遵循的约定):
// in venueService:
func someArgAndClosureFunction(arg1: String, arg2: Int,
completionClosure: (venues: Dictionary<String, AnyObject>, error: NSError?) -> ()) {
// do stuff
}
// When calling:
venueService.someArgAndClosureFunction("string arg 1", arg2: 10) {
(venues: Dictionary<String, AnyObject>, error: NSError?) -> () in
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我使用了尾随闭包语法,它允许你在函数调用parens 之外传递闭包(但它仍然作为最后一个参数传递).
| 归档时间: |
|
| 查看次数: |
6598 次 |
| 最近记录: |