这是在 Swift 中使用 get 和 set 的正式正确方法吗?

Is this officially the proper way of using get and set in Swift?

例如,我想制作某种单选按钮,它可以跟踪其活动状态并在其状态更改时更改颜色。我希望它在我设置值时改变颜色。这就是我的实现方式:

class TagButton: UIButton {

    var _active: Bool = false

    var active: Bool {
        set(newVal){
            _active = newVal
            if(!newVal){
                self.backgroundColor = UIColor.white //inactive
            }
            else {
                self.backgroundColor = UIColor.red //active
            }
        }
        get {
            return _active
        }
    }
}

现在,我看到一些问题提出了类似的方法,但令我困扰的是,这是否真的是 Swift 的预期用途。我有一种感觉,我正在在这里发明一辆自行车。我在官方 Swift 文档中找不到任何相关信息。有人能够证实这一点吗?

您的代码看起来像 Objective-C。在Swift中,不需要创建后备存储,可以使用属性观察者didSet改变背景颜色:

class TagButton: UIButton {
    var active = false {
        didSet {
            backgroundColor = active ? .red : .white
        }
    }
}

或者您可以使用 Computed 属性 而根本没有 active 的存储空间:

class TagButton: UIButton {
    var active: Bool {
        set {
            backgroundColor = newValue ? .red : .white
        }
        get {
            return backgroundColor == .red
        }
    }
}

您可以阅读更多关于 属性 观察者计算属性 here.