Retrieve only the keys & values which I stored in UserDefaults

Viewed 416

I have created UserDefaults with suite,

self.moviesWatchedUserDefaults = UserDefaults(suiteName: "com.apple.tv.2020")

And storing the info in the plist like

self.moviesWatchedUserDefaults.set(data, forKey: key).

Now, while retrieving, I wanted to retrieve all keys & values. For which I am using,

var watchedList = self.moviesWatchedUserDefaults?.dictionaryRepresentation()

But the list which is returned not only contains the items which I stored, but also other keys like NSLanguages, AppleKeyboards, AppleKeyboardsExpanded, CarCapabilities, etc.,

How to retrieve all the keys&values (only the ones which I stored) ?

1 Answers

If you have a full list of known keys, you can filter the dictionary.

In the following example I have all my known keys in an enum and I can filter the dictionary, keeping only my keys:

enum UserDefaultsKey: String, CaseIterable {
    case foo
    case bar
    case baz
}

let userDefaults = UserDefaults.standard
userDefaults.set(42, forKey: UserDefaultsKey.foo.rawValue)

let onlyMyValues = userDefaults.dictionaryRepresentation().filter { (key, _) -> Bool in
    UserDefaultsKey.allCases.map { $0.rawValue }.contains(key)
}

print(onlyMyValues) // prints ["foo": 42]
Related