all*_*bto 3 closures block swift
我想快速创建一个使用通用闭包(块)的函数。
我的第一个尝试是这样做:
func saveWithCompletionObject(obj : AnyObject, success : AnyObject -> Void, failure : Void -> Void)
Run Code Online (Sandbox Code Playgroud)
但是,一旦我用另一个块调用此函数,例如:
func doSomething(success : String -> Void, failure : Void -> Void)
{
saveWithCompletionObject("Example", success, failure)
}
Run Code Online (Sandbox Code Playgroud)
我得到一个错误: 'AnyObject' is not a subtype of 'String'
提前致谢 !
您不能将type的闭包传递给type String->Void的参数AnyObject->Void。
但是,您可以定义一个通用函数:
func saveWithCompletionObject<T>(obj : T, success : T -> Void, failure : Void -> Void) {
// ...
success(obj)
}
Run Code Online (Sandbox Code Playgroud)
现在,编译器可以验证obj与的参数具有相同的类型success,例如:
func doSomething(success : String -> Void, failure : Void -> Void)
{
saveWithCompletionObject("Example", success, failure)
}
func doSomethingElse(success : Int -> Void, failure : Void -> Void)
{
saveWithCompletionObject(13, success, failure)
}
Run Code Online (Sandbox Code Playgroud)
但我建议saveWithCompletionObject仅使用一个Void->Void
参数(不使用泛型):
func saveWithCompletionObject(success : Void -> Void, failure : Void -> Void) {
// ...
success()
}
Run Code Online (Sandbox Code Playgroud)
和呼叫者包装其关闭:
func doSomething(success : String -> Void, failure : Void -> Void)
{
saveWithCompletionObject( { success("Example") } , failure)
}
func doSomethingElse(success : Int -> Void, failure : Void -> Void)
{
saveWithCompletionObject( { success(13) }, failure)
}
Run Code Online (Sandbox Code Playgroud)
这更加灵活,例如,对于具有多个参数的回调函数:
func andNowForSomethingCompletelyDifferent(success : (Int, Double) -> Void, failure : Void -> Void)
{
saveWithCompletionObject( { success(13, M_PI) }, failure)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5592 次 |
| 最近记录: |