简体   繁体   English

为什么类型不符合协议?

[英]Why does the type not conform to protocol?

Let's have the following piece of code: 我们有以下代码:

protocol ItemView {

    var image: UIImage? { get set }
}

 class BaseController<T: UIView where T: ItemView>: UIViewController {

    var itemView = T()
}

class ConcreteItemController: BaseController<UIImageView> {

}

For the BaseController I am getting an error message saying "Type "UIImageView" does not conform to protocol "ItemView"". 对于BaseController,我收到一条错误消息,说“类型”UIImageView“不符合协议”ItemView“”。

But why? 但为什么?

Same error message shows up when I do this instead: 我执行此操作时会显示相同的错误消息:

 typealias ConcreteItemController = BaseController<UIImageView> 

I am really missing something here...why would the UIImageView not conform to ItemView protocol? 我真的在这里遗漏了一些东西......为什么UIImageView不符合ItemView协议? It HAS an optional image property..so where's the problem? 它有一个可选的图像属性..那么问题出在哪里?

UIImageView does not declare that it conforms to ItemView . UIImageView没有声明它符合ItemView Because swift is a strictly typed language, it doesn't infer conformance to protocols, as some types will only incidentally conform. 因为swift是一种严格类型的语言,它不会推断出与协议的一致性,因为某些类型只会偶然符合。 You could however say something like: 你可以这么说:

protocol ItemView {

    var image: UIImage? { get set }
}

class BaseController<T: UIView where T: ItemView>: UIViewController {

    var itemView = T()
}

extension UIImageView: ItemView {}

class ConcreteItemController: BaseController<UIImageView> {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM