2

Say I have an array of Strings with a didSet:

var bar: [String] = [] {
    didSet {
        println("Set to \(bar)")
    }
}

Setting some elements gives us:

bar = ["Hello", "world"] // Set to [Hello, world]
bar[0] = "Howdy" // Set to [Howdy, world]

Question: in my didSet, how do I get the index of the element which was set?

1 Answer 1

1

You don't have direct access to the index of the changed element, in part because setting a new value at a particular index is only one action that will trigger the didSet handler. Any mutating method will result in a call:

bar = ["Hello", "world"]                       // Set to [Hello, world]
bar[0] = "Howdy"                               // Set to [Howdy, world]
bar.insert("cruel", atIndex: 1)                // Set to [Howdy, cruel, world]
bar.replaceRange(0..<1, with: ["So", "long"])  // Set to [So, long, cruel, world]
bar.removeRange(2..<3)                         // Set to [So, long, world]
bar.append("!")                                // Set to [So, long, world, !]
bar.removeAll()                                // Set to []

Inside the didSet handler, you do have access to a special variable named oldValue, which contains the previous value of the observed variable. If you need more than that you'd need to implement a struct or class that uses an Array for storage but provides its own true accessor methods.

Sign up to request clarification or add additional context in comments.

4 Comments

Ok... that makes sense. So, maybe the question is actually: if you were to override the subscript() method for the array, what would that look like? I'm lost on the syntax at that point...
The problem there is that Array is a struct, so you can't subclass and override the subscript. (This is the part where Objective-C stalwarts begin to gnash their teeth.) You'd need to create a whole new type, with an Array as a property and the logic you want in its subscript and get/set methods.
What's your use case? Is this an array you'll be creating and working with completely, or are you trying to monitor the changes in an array from somewhere else?
It's the later -- the array is a property, and I want to know when it changes. (Yes, there are other ways to implement that functionality, but I wanted to know if there was some clever way of doing it in this spiffy new language!). I wonder if it's possible to implement this an extension to Array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.