Gene De Lisa
Gene De Lisa

Reputation: 3838

observe changes to array of structs

How do you observe additions/deletions to an array of structs?

If it were an array of classes, you could make the array dynamic and use KVO. With structs you run into problems with @objc or @objcMembers in iOS 11

Upvotes: 0

Views: 927

Answers (2)

Ole Begemann
Ole Begemann

Reputation: 135548

Do you control the definition of the array? If so, you can add a didSet observer:

var array: [MyStruct] {
    didSet {
        // do something with array and/or oldValue
    }
}

This will be called every time the array or one of its elements is mutated.

Upvotes: 2

Gene De Lisa
Gene De Lisa

Reputation: 3838

Ole is right. FWIW Here's how I tested it

struct MyStruct : CustomStringConvertible {
    var thing = "thing"

    init(_ s:String) {
        print("struct \(#function)")
        thing = s
    }
    var description:String {
        get {
            return "\(thing)"
        }
    }
}

class Foo {
    var a:[MyStruct] {
        didSet {
            print("didSet: a was set \(a)")
        }
    }

    init() {
        print("class \(#function)")
        a = [MyStruct("from Init")]
    }

    func blammo() {
        print("\(#function)")
        print("adding")
        a.append(MyStruct("Added"))
        print("new a \(a)")
    }
}

let foo = Foo()
foo.blammo()

Upvotes: 0

Related Questions