Search code examples
swiftprotocols

Swift: Default value for properties in Protocol


I am trying to provide a default value for a variable in a Protocol. I am getting an error:

Type ViewController does not conform to protocol Test

Code:

protocol Test {
    var aValue: CGFloat { get set }
}

extension Test {
    var aValue: CGFloat {
        return 0.3
    }
}


class ViewController: UIViewController, Test {

    override func viewDidLoad() {
       super.viewDidLoad()
       print("value \(aValue)")
    }
}

How can I provide a default value so the ViewController can use the default value (in the protocol extension) without to declaring it?


Solution

  • protocol Test {
        var aValue: CGFloat { get set }
    }
    
    extension Test {
        var aValue: CGFloat {
            get {
                return 0.3
            }
            set {
                print("the new value is \(newValue)")
            }
        }
    }
    
    class Default: Test {
        init() {
            print("value \(aValue)")
        }
    }
    
    
    class ViewController: Test {
    
        var aValue: CGFloat {
            get {
                return 0.4
            }
            set {
                print("i am overriding the setter")
            }
        }
    
        init() {
            print("value \(aValue)")
        }
    }
    
    var d = Default() // value 0.3
    d.aValue = 1 // the new value is 1.0
    
    var vc = ViewController() // value 0.4
    vc.aValue = 1 // i am overriding the setter
    

    Since you have a protocol extension, you don't have to implement neither the getter nor the setter if you don't want to.

    https://docs.swift.org/swift-book/LanguageGuide/Properties.html#//apple_ref/doc/uid/TP40014097-CH14-ID259

    In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

    You can't set the value of the same variable in the setter itself.