[swift-users] strange property observer behavior
adelzhang at qq.com
adelzhang at qq.com
Sun Sep 4 22:35:18 CDT 2016
Hi,
The following code works fine. The property `a` is stored twice. But
it don't enter infinite loop.
class Foo {
var a: Int = 0 {
didSet {
a = a + 1
}
}
}
let foo = Foo()
foo.a = 2
print(foo.a) // output 3
Regards
--adel
在 Mon, 05 Sep 2016 00:27:16 +0800,Gerard Iglesias
<gerard_iglesias at me.com> 写道:
> Hi,
>
> didSet is called as soon as the property is stored… Excepted when the
> value is stored in the initialiser code.
>
> For me it is completely predictable that your code enter an infinite loop
>
> Regards
>
>
>> On 4 Sep 2016, at 17:11, adelzhang via swift-users
>> <swift-users at swift.org> wrote:
>>
>> Thanks for reply.
>>
>> How does Swift choose *rules* as you said?
>>
>> Swfit encourage to override the property observer. But when we change
>> the own property in Child class's `didSet` observer, that would cause
>> infinite loop:
>>
>> class Base {
>> var a: Int = 0
>> }
>>
>> class Child : Base {
>> override var a: Int {
>> didSet {
>> a = a + 1
>> }
>> }
>> }
>>
>> let child = Child()
>> child.a = 3
>>
>> Any differcen with situation 1?
>>
>>
More information about the swift-users
mailing list