mathonsunday
3/12/2019 - 2:02 PM

Mocking UserDefaults in a playground

import Foundation
import PlaygroundSupport

var userDefaults = UserDefaults(suiteName: #file)
userDefaults!.removePersistentDomain(forName: #file)
let storageNameSpacePrefix = "favorite_events_"

func isFavorited(artistId: String) -> Bool {
    return userDefaults!.dictionaryRepresentation().keys.contains(artistIdKey(artistId: artistId))
}

func isFavoritedStandard(artistId: String) -> Bool {
    return UserDefaults.standard.dictionaryRepresentation().keys.contains(artistIdKey(artistId: artistId))
}

func save(artistId: String) {
    let artistIdData = encode(artistId: artistId)
    let key = artistIdKey(artistId: artistId)
    userDefaults!.set(artistIdData, forKey: key)
}

func remove(artistId: String) {
    let key = artistIdKey(artistId: artistId)
    userDefaults!.removeObject(forKey: key)
}

private func artistIdKey(artistId: String) -> String {
    return "\(storageNameSpacePrefix)\(artistId)"
}

private func encode(artistId: String) -> NSData? {
    do {
        let data = try NSKeyedArchiver.archivedData(withRootObject: artistId, requiringSecureCoding: true) as NSData
        return data
    } catch {
        NSLog("Error encoding event id")
        return nil
    }
}

save(artistId: "id")
print(isFavorited(artistId: "id"))
print(isFavoritedStandard(artistId: "id"))
userDefaults!.removePersistentDomain(forName: #file)
print(isFavorited(artistId: "id"))