Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get notified when element added/removed to array

Tags:

arrays

ios

swift

I wanted to be notified when an element added/removed from an array. If we are not talking about arrays, for example to be notified when a string is changed, there is a good solution in swift:

private var privateWord: String?
var word: String? {
    get {
        return privateWord
    }
    set {
        if newValue != "" {
            notifyThatWordIsChanged()
        } else {
            notifyThatWordIsEmpty()
        }
        privateWord = newValue
    }
}

Can we achive a similar result, when I add/remove an element to an array?

like image 844
Dániel Nagy Avatar asked Nov 20 '14 14:11

Dániel Nagy


Video Answer


1 Answers

You can create proxy like class/struct that will have same interface as array, will store standard array under the scenes and will act on behalf of store array. Here is small example:

struct ArrayProxy<T> {
    var array: [T] = []

    mutating func append(newElement: T) {
        self.array.append(newElement)
        print("Element added")
    }

    mutating func removeAtIndex(index: Int) {
        print("Removed object \(self.array[index]) at index \(index)")
        self.array.removeAtIndex(index)
    }

    subscript(index: Int) -> T {
        set {
            print("Set object from \(self.array[index]) to \(newValue) at index \(index)")
            self.array[index] = newValue
        }
        get {
            return self.array[index]
        }
    }
}

var a = ArrayProxy<Int>()
a.append(1)
like image 134
Kirsteins Avatar answered Sep 28 '22 07:09

Kirsteins