[英]Cannot convert return expression of generic protocol's function type implementation
I'd like to use swift generics in a way described below: 我想以下面描述的方式使用swift泛型:
class ResponseContainer {
}
protocol DisplayManageable {
func getModel<ModelType: ResponseContainer>() -> ModelType?
}
class DisplayBaseManager<ObtainedModelType: ResponseContainer>: NSObject, DisplayManageable {
var modelObtained: ObtainedModelType? = nil
func getModel<ObtainedModelType>() -> ObtainedModelType? {
return modelObtained
}
}
But I have a problem with this code, more precisely there is a problem in this line: 但是这个代码有问题,更确切地说这行有一个问题:
return modelObtained
And I'm getting the error: 我收到了错误:
Cannot convert return expression of type 'ObtainedModelType?'
无法转换'ObtainedModelType?'类型的返回表达式 to return type 'ObtainedModelType?'
返回类型'ObtainedModelType?'
And now my simple question, why can't I do that? 现在我的简单问题,为什么我不能这样做? What's wrong with that?
这有什么问题?
Generics in protocol's function and in class definitions are the same. 协议函数和类定义中的泛型是相同的。 Everything looks fine in my opinion and logically is ok, so why cannot I do so?
在我看来,一切看起来都很好,从逻辑上来说还可以,所以为什么我不这样做呢?
In 在
func getModel<ObtainedModelType>() -> ObtainedModelType? { ... }
ObtainedModelType
introduces a local generic placeholder, and that hides the ObtainedModelType
from the class definition ObtainedModelType
引入了一个本地通用占位符,并从类定义中隐藏了ObtainedModelType
class DisplayBaseManager<ObtainedModelType: ResponseContainer>
This causes the strange looking error message 这会导致奇怪的错误消息
Cannot convert return expression of type 'ObtainedModelType?'
无法转换'ObtainedModelType?'类型的返回表达式 to return type 'ObtainedModelType?'
返回类型'ObtainedModelType?'
because return modelObtained
has the generic type ObtainedModelType?
因为
return modelObtained
具有泛型类型return modelObtained
ObtainedModelType?
from the class definition, but the expected return type is ObtainedModelType?
从类定义,但预期的返回类型是
ObtainedModelType?
from the method definition. 从方法定义。
What you probably want is a protocol with an associated type 您可能需要的是具有关联类型的协议
protocol DisplayManageable {
associatedtype ModelType: ResponseContainer
func getModel() -> ModelType?
}
and a class adopting this protocol with ModelType == ObtainedModelType
: 和一个采用
ModelType == ObtainedModelType
协议的类:
class DisplayBaseManager<ObtainedModelType: ResponseContainer>: NSObject, DisplayManageable {
var modelObtained: ObtainedModelType? = nil
func getModel() -> ObtainedModelType? {
return modelObtained
}
}
Łukasz, I don't now why it doesn't compile but I found the way to compile it. Łukasz,我现在不知道它为什么不编译,但我找到了编译它的方法。 Just change the return statement:
只需更改return语句:
return modelObtained as? ObtainedModelType
But I'm still waiting for someone to explain the reason for error in the original code. 但我仍在等待某人解释原始代码中出错的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.