Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 460
user1107173 Avatar asked Oct 16 '25 09:10

user1107173


1 Answers

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.

like image 176
Huy-Anh Hoang Avatar answered Oct 19 '25 11:10

Huy-Anh Hoang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!