So here is a thing I wanted to use the protocol oriented programming paradigm with the OOP to have some of variables assigned to main classes like let's say UIView, UIImageView etc. but then have some other variables defined in their subclasses. To achieve that one need to make those variables "optional" and is Swift a way to do that is to extend a protocol. Everything works great until I decide to add those subclasses instances to an array and read those variables later... That is the very same object (same pointer) but when reading that variable after adding to an array it uses a getter from the protocol extension not the one from the subclass.
protocol SomeProtocol {
var foo: String { get }
var foo2: String { get }
}
extension SomeProtocol {
var foo2: String {
return "value from extension"
}
}
extension UIView: SomeProtocol {
var foo: String {
return "value from UIView"
}
}
class SomeView: UIView {
var foo2: String {
return "value from someView"
}
}
let someView = SomeView()
print(someView.foo2)
"value from someView"
var array = [SomeProtocol]()
array.append(someView)
print(array.first?.foo2)
"value from extension"
I know that it's an array of objects conforming to the SomeProtocol
and that's probably a reason. The thing is I want to have an array of objects of different classes conforming to that protocol and be able to access a getter from those objects not from the protocol extension. It would be probably possible if I use an @objc
protocol and an optional
variable but I would prefer to have pure Swift solution.