Renuka Pandey
Renuka Pandey

Reputation: 1810

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?

Upvotes: 34

Views: 25450

Answers (2)

Alexandre G.
Alexandre G.

Reputation: 1779

If you want to conform to Swift's documentation, you'd have to implement it like this :

@objc protocol Named {
    // variables
    var name: String { get }
    @objc optional var age: Int { get }
  
    // methods
    func addTen(to number: Int) -> Int
    @objc optional func addTwenty(to number: Int) -> Int
}

class Person: Named {
    var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func addTen(to number: Int) -> Int {
        return number + 10
    }
}

Upvotes: 10

Renuka Pandey
Renuka Pandey

Reputation: 1810

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

Upvotes: 56

Related Questions