Earl Grey Earl Grey - 4 months ago 20
Swift Question

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"".

But why?

Same error message shows up when I do this instead:

typealias ConcreteItemController = BaseController<UIImageView>


I am really missing something here...why the hell would the UIImageView not conform to ItemView protocol? It HAS an optional image property..so where's the problem?

Answer

UIImageView does not declare that it conforms to ItemView and the compiler is not smart enough to infer such. You could however say something like:

protocol ItemView {

    var image: UIImage? { get set }
}

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

    var itemView = T()
}

class ImageView: UIImageView, ItemView {}

class ConcreteItemController: BaseController<ImageView> {

}