Are variables in the protocol 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 the variables to be optional, so I don’t need to execute all the variables every time after the corresponding protocol. As in Objective-C, we did for the 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?

+4
source share
2 answers
protocol TestProtocol {
    var name : String {set get}
    var age : Int {set get}
}

Provide the default extension for the protocol. Provide a default implementation for all given variables and get what they want them to be optional.

In the protocol below, 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 follow the above protocol for any other class, for example

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

Swift, :

@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
    }
}
0

Source: https://habr.com/ru/post/1678339/


All Articles