didSet and depthy recursion.

ran into an issue, I know I can work around it. But I really want to understand it.

I wrote a code example in a playground :


import Cocoa

class aClass {
    var anArray : [String] = ["base"]{
            for each in subs{
                for eachEntry in anArray{
                    if each.anArray.contains(eachEntry) == false{
                        each.anArray += [eachEntry]
    var subs : [aClass] = []

// instance the class
let newInstance = aClass()

// add a few subs
newInstance.subs += [aClass(), aClass(), aClass()]

// now make a special sub:
let specSub = aClass()
// and add it as a child of the last sub in newInstance
newInstance.subs[2].subs += [specSub]

// now we test the depthy nature of a didSet
newInstance.anArray += ["foo"]

let newVal = specSub.anArray



now, my expectation was that when i set the value of anArray, and it in turn set the value of it’s sub-object’s anRayy properties, that the observation would be triggered. in concrete terms: when I added “foo” to the parent object, “foo” would be added to all children and children of chidlren of the parent object.


but it isn’t. What I’m wondering is: why?

Powered by WPeMatico


You may also like...

Comments are closed.