[英]Swift generics Bool is not convertible to Bool
I have written a protocol like: 我写了一个类似的协议
public protocol Protocol1 {
func execute<T, R>(req: T) -> Promise<R>
}
Implemented the protocol as Below: 实现了如下协议:
struct Implemented1 : Protocol1 {
func execute<String, Bool>(req : String) -> Promise<Bool> {
return Promise<Bool>() { fulfill, reject in
fulfill(true)
}
}
}
I am getting following error: 我收到以下错误:
'Bool' is not convertible to 'Bool' “布尔”不能转换为“布尔”
Please help me to understand what is the issue. 请帮助我了解问题所在。
The problem is at the start of the method declaration. 问题出在方法声明的开始。
func execute<String, Bool>
Who taught you to declare a generic method this way? 谁教您以这种方式声明泛型方法?
The generic parameters are supposed to go in the <>
s, not actual types! 通用参数应该放在
<>
而不是实际类型中!
To implement the protocol, you need a generic method, not one that accepts a String
and returns Bool
. 要实现该协议,您需要一种通用方法,而不是接受
String
并返回Bool
。
So the compiler treats String
and Bool
as names of the generic parameters, instead of the actual swift types. 因此,编译器将
String
和Bool
视为通用参数的名称,而不是实际的swift类型。 So when the compiler says that Bool
cannot be converted to Bool
, it actually means that the swift Bool
type cannot be converted to the generic parameter Bool
. 所以,当编译器表示,
Bool
不能转换为Bool
,这实际上意味着迅速Bool
类型不能转换为泛型参数Bool
。
I think what you need is associated types. 我认为您需要的是关联类型。
public protocol Protocol1 {
associatedtype RequestType
associatedtype ResultType
func execute(req: RequestType) -> Promise<ResultType>
}
struct Implemented1 : Protocol1 {
typealias ResultType = Bool
typealias RequestType = String
func execute(req : String) -> Promise<Bool> {
return Promise { fulfill, reject in
fulfill(true)
}
}
}
PS this: PS:
Promise { fulfill, reject in
fulfill(true)
}
can be simplified to: 可以简化为:
Promise(value: true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.