[swift-users] struct property changing calls didSet of the Struct each time, but class won't

Zhao Xin owenzx at gmail.com
Mon Nov 13 09:06:29 CST 2017


Hi everyone,

See below codes,

//: Playground - noun: a place where people can play


import Foundation


struct Foo {

    var bar = 0

}


class A {

    var foo = Foo() {

        didSet {

            print("foo changed")

        }

    }

}


let a = A()


for i in 1...5 {

    a.foo.bar = i

}


// prints five times

// foo changed

// foo changed

// foo changed

// foo changed

// foo changed


If I change `struct Foo` to `class Foo`, nothing will happen.

My code depends on the class version didSet but I used the struct version.
It took me a long time to debug this out. Is this a knowledge that has been
well known already?

Xcode 9.1, Swift 4.0.2


Zhao Xin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171113/c74bf6b3/attachment.html>


More information about the swift-users mailing list