ios swift willSet didSet 并获取属性中的设置方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25398753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:57:27  来源:igfitidea点击:

swift willSet didSet and get set methods in a property

iosswiftpropertiesdidset

提问by just ME

What is the difference between willSet- didSet, and get- set, when working with this inside a property?

在属性中使用 this 时willSet-didSetget-之间有什么区别set

From my point of view, both of them can set a value for a property. When, and why, should I use willSet- didSet, and when get- set?

在我看来,他们都可以为一个属性设置一个值。什么时候,为什么,我应该使用willSet- didSet,什么时候get- set

I know that for willSetand didSet, the structure looks like this:

我知道对于willSetand didSet,结构如下所示:

var variable1 : Int = 0 {
    didSet {
        println (variable1)
    }
    willSet(newValue) {
    ..
    }
}

var variable2: Int {
    get {
        return variable2
    }
    set (newValue){
    }
}

回答by Maxim Shoustin

When and why should I use willSet/didSet

我何时以及为什么应该使用 willSet/didSet

  • willSetis called just beforethe value is stored.
  • didSetis called immediately afterthe new value is stored.
  • willSet存储值之前调用。
  • didSet存储新值立即调用。

Consider your example with outputs:

考虑您的输出示例:



var variable1 : Int = 0 {
        didSet{
            print("didSet called")
        }
        willSet(newValue){
            print("willSet called")
        }
    }

    print("we are going to add 3")

     variable1 = 3

    print("we added 3")

Output:

输出:

we are going to add 3
willSet called
didSet called
we added 3

it works like pre/post -condition

它像前置/后置条件一样工作

On the other hand, you can use getif you want to add, for example, a read-only property:

另一方面,get如果要添加例如只读属性,则可以使用:

var value : Int {
 get {
    return 34
 }
}

print(value)

value = 2 // error: cannot assign to a get-only property 'value'

回答by Antonio

@Maxim's answer is for the 1st part of your question.

@Maxim 的回答是针对您问题的第一部分。

As for when to use getand set: when you want a computed property. This:

至于何时使用getset:何时需要计算属性。这个:

var x: Int

creates a stored property, which is automatically backed up by a variable (not directly accessible though). Setting a value to that property is translated in setting the value in the property, and similarly for getting.

创建一个存储属性,它由一个变量自动备份(虽然不能直接访问)。为该属性设置值被转换为在属性中设置值,并且与获取类似。

Instead:

反而:

var y = {
    get { return x + 5 }
    set { x = newValue - 5}
}

will create a computed property, which is not backed up by a variable - instead you have to provide the implementation of the getter and/or setter, usually reading and writing values from another property and more generally as a result of a computation (hence the computed propertyname)

将创建一个不由变量支持的计算属性 - 相反,您必须提供 getter 和/或 setter 的实现,通常从另一个属性读取和写入值,更一般地作为计算的结果(因此计算属性名称)

Suggested reading: Properties

推荐阅读:属性

Note: your code:

注意:您的代码:

var variable2: Int {
    get{
        return variable2
    }
    set (newValue){
    }
}

is wrongbecause in the getyou are trying to return itself, which means calling getrecursively. And in fact the compiler will warn you with a message like Attempting to access 'variable2' within its own getter.

错误的,因为在get您试图返回自身时,这意味着get递归调用。事实上,编译器会用类似Attempting to access 'variable2' within its own getter.

回答by NiravS

var variable1 : Int = 0 { //It's a store property
    didSet {
        print (variable1)
    }
    willSet(newValue) {
    ..
    }
}

var variable2: Int { //It's a Computed Proprties
    get {
        return variable2
    }
    set (newValue){
    }
}

For detail info of Store property and computed property
So when you are trying to assign the value into variable at that assigning time come the concept of 'didSet' & 'willSet'. As @Maxim says

有关Store 属性和计算属性的详细信息
因此,当您在分配时尝试将值分配给变量时,会出现“didSet”和“willSet”的概念。正如@Maxim 所说

  • willSetis called just beforethe value is stored.
  • didSetis called immediately afterthe new value is stored.
  • willSet在值被存储之前被调用。
  • didSet存储新值立即调用。


Example of 'willSet' & 'didSet' :


'willSet' 和 'didSet' 示例:

class Number {
   var variable1 : Int = 0 {
        didSet{
            print("didSet called")
        }
        willSet(newValue){
            print("willSet called")
        }

    }
}
print("we are going to add 3")
Number().variable1 = 3
print("we added 3")

//o/p:
we are going to add 3
willSet called
didSet called
we added 3

//o/p:
我们要添加 3 个
willSet 调用
didSet 调用
我们添加了 3

And generally when two property are dependent at that time 'get' & 'set' used. (It's also used in protocolthis is different concept.)

通常当两个属性依赖时,会使用 'get' 和 'set'。(它也用于协议中,这是不同的概念。)

Example of 'get' & 'set':

“获取”和“设置”的示例:

class EquilateralTriangle{
    var sideLength: Double = 0.0
    init(sideLength: Double){
        self.sideLength = sideLength
    }
    var perimeter: Double {
        get {
            return 3.0 * sideLength
        }
        set {
            sideLength = newValue / 3.0
        }
    }

}

var triangle = EquilateralTriangle(sideLength: 3.0)
print(triangle.perimeter) //o/p: 9.0
triangle.perimeter = 12.0
print(triangle.sideLength) //o/p: 4.0

回答by Hyman

get set:

设置

getsetare Computed PropertiesWhich do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly

getset计算属性实际上并不存储值。相反,它们提供了一个 getter 和一个可选的 setter 来间接检索和设置其他属性和值

Additionally you can define Read-Only Computed Properties. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value

此外,您可以定义只读计算属性。只读计算属性总是返回一个值,可以通过点语法访问,但不能设置为不同的值

Example get only property-

示例仅获取属性-

 var number: Double {
        return .pi*2
    }

willSet didSet:

willSet didSet

willSetdidSetare Property Observers

Property observers observe and respond to changes in a property's value. Property observers are called every time a property's value is set, even if the new value is the same as the property's current value.

willSetdidSet物业观察员

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

  • willSet is called just before the value is stored.
  • didSet is called immediately after the new value is stored.
  • willSet 在值被存储之前被调用。
  • didSet 在存储新值后立即调用。

Example -

例子 -

var score: Int = 0 {
    willSet(newScore) {
        print("willSet  score to \(newScore)")
    }
    didSet {
        print("didSet score to \(oldValue) new score is: \(score)")
    }
}
score = 10
//Output 
//willSet  score to 10
//didSet score to 0 new score is: 10

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html