Search code examples
swiftprotocols

Optional Variables in protocol is possible?


protocol AProtocol: BProtocol {
    /// content to be shown on disclaimer Label of cell
    var disclaimer: String {get set}
    var cellDisclaimerAttributed: NSAttributedString {get}
    var showSelection: Bool {get set}
    var isReadMore: Bool {get}
}

I want to make variables optional so that I need not implement all variables every time after conforming protocol. Like in Objective-C we did for methods:

protocol AProtocol: BProtocol {
    /// content to be shown on disclaimer Label of cell
    optional var disclaimer: String {get set}
    optional var cellDisclaimerAttributed: NSAttributedString {get}
    optional var showSelection: Bool {get set}
    optional var isReadMore: Bool {get}
}

Is it possible?


Solution

  • 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 {}
        }
    }