Optional Variables in protocol is possible?

protocol TestProtocol {
    var name : String {set get}
    var age : Int {set get}
}

Provide a default extension for the protocol. Provide the default implementation for all the variables set and get which u want them to be optional.

In below protocol, name and age are optional.

 extension TestProtocol {

    var name: String {
        get { return "Any default Name" } set {}
    }  
    var age : Int { get{ return 23 } set{} }      
}

Now if I am conforming above protocol to any other class, like

class TestViewController: UIViewController, TestProtocol{
        var itemName: String = ""

**I can implement the name only, and my objective is achieved here, that the controller will not give a warning that "TestViewController does not conform to protocol TestProtocol"**

   var name: String {
        get {
            return itemName ?? ""
        } set {}
    }
}

Leave a Comment

techhipbettruvabetnorabahisbahis forumu