brandonscript
brandonscript

Reputation: 72925

Save updated Set in UserDefaults every time .insert() or .remove(at:) are called

I’m sure this is a silly question, but I’m on a phone, and can’t find any similar questions.

I have a Set:

var mySet: Set<SomeObject>

That I need to persist across app launches, presumably using UserDefaults.

This works ok if I re-create and re-save the Set to UserDefaults every time it is modified, but that seems awfully cumbersome. Is there a way I can support updating the UserDefaults value every time .insert() or .remove(at:) are called?

Upvotes: 1

Views: 217

Answers (1)

Martin R
Martin R

Reputation: 539835

You can use a property observer for that purpose. Here is a simple example for a set of integers (saved as an array):

var mySet = Set(UserDefaults.standard.array(forKey: "mySet") as? [Int] ?? []) {
    didSet {
        // Save new value
        UserDefaults.standard.set(Array(mySet), forKey: "mySet")
    }
}

Set is a value type, and therefore each modification (insertion, removal, ...) stores a new value in the variable, and the property observer is triggered.

Upvotes: 3

Related Questions