与 struct 中定义的 Void 回调相关的 Swift 编译器错误的解决方法/解决方案 [英] Workaround/resolution for Swift compiler error related to Void callback defined in struct
问题描述
由于 Swift 中 typealias
定义缺乏通用支持,我编写了一个通用的 ResultHandler
回调,如下所示:
Due to the lack of generic support in typealias
definitions in Swift, I wrote a generic ResultHandler<T>
callback like so:
struct ResultHandler<T> {
let f: (result: T) -> ()
}
这对于使用 Void
以外的任何东西的处理程序非常有用:
This works great for handlers that use anything other than Void
:
Dispatch<Bool>.dispatch({ () -> (Result<Bool>) in
Result<Bool>(true)
}).onResult(ResultHandler() { (result: Bool) in
if result {
self.doSomething() // Method executes successfully
}
})
但是当尝试使用 Void
时:
But when attempting to use Void
:
Dispatch<Void>.dispatch({ () -> (Result<Void>) in
Result<Void>()
}).onResult(ResultHandler() { (result: Void) in // Compiler error here
self.doSomething()
})
存在编译错误:
函数签名'(Void) -> ()' 与预期类型不兼容'(结果:无效)-> ()'
Function signature '(Void) -> ()' is not compatible with expected type '(result: Void) -> ()'
这似乎误导/编译器错误,好像我更改了签名以使用错误类型的值:
Which seems misleading/a compiler bug, as if I change the signature to use a wrongly-typed value:
Dispatch<Void>.dispatch({ () -> (Result<Void>) in
Result<Void>()
}).onResult(ResultHandler() { (result: Void?) in // Compiler error here
self.doSomething()
})
错误消息选择了可选的指示 ?
,但仍然没有正确检测到我的 result:
标签:
The error message picks up the optional-indicating ?
, but still does not properly detect my result:
label:
函数签名'(Void?) -> ()' 与预期类型不兼容'(结果:无效)-> ()'
Function signature '(Void?) -> ()' is not compatible with expected type '(result: Void) -> ()'
我做错了什么?
推荐答案
您不需要在闭包类型声明中指定参数名称——这就是编译器出现问题的原因:
You don't need to specify parameter names in closure type declarations—that's what's giving the compiler problems:
struct ResultHandler<T> {
let f: T -> ()
}
现在您可以创建使用 Bool
参数、Void
参数或完全省略参数的 ResultHandler
实例:
Now you can create ResultHandler
instances that use a Bool
parameter, a Void
parameter, or leave out the parameter altogether:
let r1 = ResultHandler() { (result: Bool) in
if result {
// do something
}
}
let r2 = ResultHandler() { (_: Void) in
// do something
}
let r3 = ResultHandler() {
// do something
}
这篇关于与 struct 中定义的 Void 回调相关的 Swift 编译器错误的解决方法/解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!