Swift: Key Value Observing Collections

409 views Asked by At

I've read the Swift documentation on Key-Value Observing.

But, how do I implement key-value observing for collections in Swift?

Here's the relevant Object-C documentation that's missing for Swift:

1

There are 1 answers

0
Sez On

This works for me:

class Document: NSDocument {

    var rooms = [Room]()

    func insertObject(room: Room, inRoomsAtIndex index: Int)
    {
        // Do something interesting 
        NSLog("Adding \(room) to \(rooms)")

        // Perform the actual insert
        rooms.insert(room, atIndex: index)
    }

    func removeObjectFromRoomsAtIndex(index: Int)
    {
        let room = rooms[index]
        NSLog("Removing room \(room)")


        // Perform the actual remove
       rooms.removeAtIndex(index)
    }

    // ...
}    

I got to this by translating the expected Obj-C KV signatures to Swift for the methods I was interested in. You should be able to get the others (for unordered to-many) working the same way.