Properties 为已定义getter和setter的属性设置默认值

Properties 为已定义getter和setter的属性设置默认值,properties,swift,Properties,Swift,我有一门很简单的课 class SimpleClass { var simpleDescription: String { get { return self.simpleDescription } set { self.simpleDescription = newValue } } } 为simpleDescription变量定义默认值的正确方法是什么?在Swift中,getter和setter用于计算属性-属

我有一门很简单的课

class SimpleClass {
    var simpleDescription: String {
    get {
        return self.simpleDescription
    }
    set {
        self.simpleDescription = newValue
    }
    }
}

simpleDescription
变量定义默认值的正确方法是什么?

在Swift中,getter和setter用于计算属性-属性没有存储空间,因此在您的情况下,
simpleDescription
不能在setter中设置

如果需要默认值,请使用:

class SimpleClass {
  var simpleDescription: String = "default description"
}
如果要初始化,请使用:

class SimpleClass {
  var simpleDescription: String
  init (desc: String) {
    simpleDescription = desc
  }
}

如果要在每次设置变量时执行操作,或者只是检查值是否正确,则可以使用
属性观察器

从文档:

属性观察者观察并响应属性值的变化。每次设置属性值时都会调用属性观察者,即使新值与属性的当前值相同

您可以这样使用它们:

class StepCounter {
    var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            print("About to set totalSteps to \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue  {
                print("Added \(totalSteps - oldValue) steps")
            }
        }
    }
}
编辑

在重写继承的属性时,这似乎不起作用。下面是一个你不能做的事情的例子:

class StepWihtoutCounter {
    var totalSteps: Int = 0 
}

class StepCounter: StepWihtoutCounter {
    override var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            print("About to set totalSteps to \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue  {
                print("Added \(totalSteps - oldValue) steps")
            }
        }
    }

直接设置简单值:

var string1: String = "value" {
    willSet {
        print("willSet")
    }
    didSet {
        print("didSet")
    }
}
设置计算闭包的结果:

var string2: String = {
        let value = "value"
        return value
    }() {
    willSet {
        print("willSet")
    }
    didSet {
        print("didSet")
    }
}

解决办法很简单。只需使用另一个变量,将其返回getter

var _simpleDescription = "Default value"

var simpleDescription: String {
    get {
        return self._simpleDescription
    }
    set {
        self.simpleDescription = newValue
    }
}

这对我来说不起作用,因为我仍然会遇到与上述问题相同的错误。使用Xcode 7.3 beta 5 7D152p。找不到原始问题中描述的任何错误,它只询问如何执行。哪个是错误?导致编译错误:
带有getter/setter的变量不能有初始值
。我是通过谷歌搜索登陆这里的,所以我只是假设海报和我有相同的错误,并没有阅读问题我可能会遇到问题,因为这是一个
覆盖
,但是…刚刚在操场上测试过,问题似乎是您不能在
覆盖
n属性上使用属性观察器。通过快速搜索,我发现了这一点,建议创建一个占位符函数,该函数从父类中的原始didSet调用,因此您只需重写它function@hhanesand编辑并添加了您的案例,以便在有人无意中发现这一点时清晰明了