protocol A {}
extension Int: A {}
extension String: A {}
enum Result<T> {
case success(T)
case error(Error)
}
typealias BaseFunc = (Result<A>) -> ()
func foo(r: Result<Int>) {}
func bar(r: Result<String>) {}
var f: BaseFunc = foo
编译器说cannot convert value of type '(Result<Int>) -> ()' to specified type 'BaseFunc' (aka '(Result<A>) -> ()')
我在Swift中尝试做的事情是什么?也许有另一种方法可以达到类似的结果?
@iWheelBuy正确回答了这个问题。但是我把它弄错了。我想要的是这样的:
protocol A {}
extension Int: A {}
extension String: A {}
enum Result<T> {
case success(T)
case error(Error)
}
typealias BaseFunc<T> = (Result<T>) -> ()
func foo(r: Result<Int>) {}
func bar(r: Result<String>) {}
var f: BaseFunc<A>
if arc4random_uniform(10) < 5 {
f = foo
} else {
f = bar
}
结果为:cannot assign value of type '(Result<Int>) -> ()' to type '(Result<A>) -> ()'
答案 0 :(得分:2)
你试过这种方式吗?
dll
您的typealias BaseFunc<B:A> = (Result<B>) -> ()
没有通用参数