Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force child classes to implement protocol swift

Tags:

swift

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

like image 851
Morgan Avatar asked Nov 27 '14 09:11

Morgan


2 Answers

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
like image 153
rintaro Avatar answered Sep 30 '22 20:09

rintaro


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

like image 22
Suresh Kumar Durairaj Avatar answered Sep 30 '22 21:09

Suresh Kumar Durairaj