How can i forced a child class to implement a protocol declared in the parent class?
I tried this:
protocol MyProtocol {
var myVar : String { get }
}
class ParentClass: MyProtocol {
var myVar = "parent"
}
class ChildClass: ParentClass {
}
But my child class doesn't force me to override myVar.
This is possible ?
Thank you very much,
Morgan
Swift does not have such feature.
All you can do is, emitting the runtime error. And you have to use computed property to override the property.
Something like this:
protocol MyProtocol {
var myVar : String { get }
}
class ParentClass: MyProtocol {
var myVar:String {
if self.dynamicType !== ParentClass.self {
fatalError("subclass must implement myVar")
}
return "parent"
}
}
class ChildClass1: ParentClass {
override var myVar:String {
return "hello"
}
}
class ChildClass2: ParentClass {
// missing myVar implementation
}
let parent = ParentClass()
parent.myVar // -> "parent"
let child1 = ChildClass1()
child1.myVar // -> "hello"
let child2 = ChildClass2()
child2.myVar // -> fatal error: subclass must implement myVar
As far as my knowledge this is not possible in Swift. If you try conforming to the parent class's protocol, Leads to an error "Cannot override with a stored property". Since the protocol is already conformed in the parentClass.
protocol MyProtocol {
var myVar : String { get }
}
class ParentClass: MyProtocol {
var myVar = "parent"
}
class ChildClass: ParentClass {
var myVar = "hello"
// Throws compilation error, "Cannot override with a stored property" since it's already conformed by the parentClass itself.
}
Added:
In general words multi-level implementation of an interface is not possible, In iOS words protocol's should be implemented at single level only. But since you've inherited the parentClass, childClass has the scope to access parentClass members.
class ChildClass: ParentClass, MyProtocol {
func printValue(){
println("newvalue : \(myVar)")
myVar = "hello"
}
}
Hope this helps...!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With