I want to declare a view that conform to a certain protocol. On one side, I need to be able to specify it is an UIView, to be able to add it as subview and also expect conformance with a protocol.
The problem started with, that I want to create a generic container for a textview which can be editable or not.
I decided that I will use different classes for this - UILabel when it's not editable and UITextField when it is. So in my generic container I want to be able to 1. add the view as a subview and 2. To be able to set the text.
UILabel and UITextField don't have a common interface to set the text, so I let them implement a new protocol using extensions:
protocol TextView {
var text_:String? {get set}
}
extension UILabel:TextView {
var text_:String? {
get {
return self.text
}
set {
self.text = newValue
}
}
}
extension UITextField: TextView {
var text_:String? {
get {
return self.text
}
set {
self.text = newValue
}
}
}
So far so good - but in my container view I need to declare the generic view either as UIView or TextView. If I do it as TextView, I have to cast in order to add them as a subview, and if I declare it as UIView, I have to cast when I want to set the text.
I would like to be able to specify (compile time) something like "this variable is a UIView that conforms to TextView protocol". How can I do this? If it's not possible what is the recommended approach to solve this kind of problem?
Thanks!