Swift:协议中属性的默认值

Swift: Default value for properties in Protocol

我正在尝试为协议中的变量提供默认值。我收到一个错误:

Type ViewController does not conform to protocol Test

代码:

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)")
    }
}

我如何提供默认值以便 ViewController 可以使用默认值(在协议扩展中)而不声明它?

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

因为你有一个协议扩展,如果你不想的话,你不必实现 getter 和 setter。

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.

您不能在 setter 本身中设置同一个变量的值。