Struct, Mutating and Property Observers

Please look at that code:

class Mut {
    
    var zetstruct = MutStr(z: 5) {
        didSet {
            print("struct was change")
            zetstruct.addZet(num: 10)
        }
    }
    
    struct MutStr {
        var z: Int
        mutating func addZet(num: Int) {
            z += num
        }
    }
    
    func work() {
        zetstruct.addZet(num: 10)
    }
}

let mut = Mut()
mut.work()

Why in this case we don't have infinity cycle? Because when we change struct's property within mutating function it cause that instance property 'zetstruct' change and didSet invocate.

···

--
Седых Александр

From the Swift book we know this:

If you assign a value to a property within its own didSet observer, the new value that you assign replaces the one that was just set.
That means that it won’t fire another didSet observer due replacing or in your case mutating.

···

--
Adrian Zubarev
Sent with Airmail

Am 7. Oktober 2016 um 17:46:37, Седых Александр via swift-users (swift-users@swift.org) schrieb:

Please look at that code:

class Mut {

var zetstruct = MutStr(z: 5) {
didSet {
print("struct was change")
zetstruct.addZet(num: 10)
}
}

struct MutStr {
var z: Int
mutating func addZet(num: Int) {
z += num
}
}

func work() {
zetstruct.addZet(num: 10)
}
}

let mut = Mut()
mut.work()

Why in this case we don't have infinity cycle? Because when we change struct's property within mutating function it cause that instance property 'zetstruct' change and didSet invocate.

--
Седых Александр
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users