How can I have a variable in Swift that has the following restrictions:
- It must conform to a specific protocol
- It must be a subclass of
UIView
- It does not need to be a direct subclass child of
UIView
(i.e. it may be a subclass of a UIButton, for example)
Note that this is similar to this (which fails to satisfy point 3).
The following also satisfies points 1 and 2 (but not 3):
protocol MyProtocol {
var onClick: Void -> Void {get set}
}
class MyCommonView: UIView, MyProtocol {
var onClick: Void -> Void = {
println("onClick!")
}
}
class MyLittleView: MyCommonView {
}
class MyBigView: MyCommonView {
}
var myView: MyProtocol!
myView = MyLittleView()
myView.onClick()
myView.backgroundColor = UIColor.redColor() // 'MyProtocol' does not have a member named 'backgroundColor'
myView = MyBigView()
myView.onClick()
myView.backgroundColor = UIColor.redColor() // 'MyProtocol' does not have a member named 'backgroundColor'
Edit
Although this is similar to this question (and answer by @zneak), it would be great to not have to specify all the UIView
methods that I want to use, I'd like to be able to use any or all of them.
Here is what I came up with based on the answer given by @zneak, can it be improved so as not to have to specify all the needed UIView methods I want to use?
protocol MyOnClickProtocol {
var onClick: Void -> Void {get set}
}
protocol MyViewProtocol {
var backgroundColor: UIColor? {get set}
// And other methods or properties of UIView that I want to access...
}
class MyLittleView: UIButton, MyOnClickProtocol, MyViewProtocol {
var onClick: Void -> Void = {
println("onClick!")
}
}
class MyBigView: UISwitch, MyOnClickProtocol, MyViewProtocol {
var onClick: Void -> Void = {
println("onClick!")
}
}
var myView: protocol<MyViewProtocol, MyOnClickProtocol>!
myView = MyLittleView()
myView.onClick()
myView.backgroundColor = UIColor.redColor()
myView = MyBigView()
myView.onClick()
myView.backgroundColor = UIColor.redColor()