Skip to content

Instantly share code, notes, and snippets.

@ArtSabintsev
Created March 22, 2017 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArtSabintsev/28e889cfd361d6b11f2029ca5570812d to your computer and use it in GitHub Desktop.
Save ArtSabintsev/28e889cfd361d6b11f2029ca5570812d to your computer and use it in GitHub Desktop.
An example on a couple ways to create keys for UserDefaults.
import Foundation
enum EnumKey: String {
case aKey = "Key A from Enum"
case bKey = "Key B from Enum"
case cKey = "Key C from Enum"
}
struct StructKey {
static let aKey = "Key A from Struct"
static let bKey = "Key B from Struct"
static let cKey = "Key C from Struct"
}
/// ENUM
// Store to Defaults
UserDefaults.standard.set(true, forKey: EnumKey.aKey.rawValue)
UserDefaults.standard.set(false, forKey: EnumKey.bKey.rawValue)
UserDefaults.standard.set(false, forKey: EnumKey.cKey.rawValue)
// Fetch from Defaults
UserDefaults.standard.bool(forKey: EnumKey.aKey.rawValue)
UserDefaults.standard.bool(forKey: EnumKey.bKey.rawValue)
UserDefaults.standard.bool(forKey: EnumKey.cKey.rawValue)
/// STRUCT + STATIC LET
// Fetch from Defaults
UserDefaults.standard.set(false, forKey: StructKey.aKey)
UserDefaults.standard.set(true, forKey: StructKey.bKey)
UserDefaults.standard.set(true, forKey: StructKey.cKey)
// Store to Defaults
UserDefaults.standard.bool(forKey: StructKey.aKey)
UserDefaults.standard.bool(forKey: StructKey.bKey)
UserDefaults.standard.bool(forKey: StructKey.cKey)
@drosenstark
Copy link

Thanks, this is very useful. Here's a little riff I did, but it's hard to think about getting much leverage with my approach:

import XCTest

// starting point was https://gist.github.com/ArtSabintsev/28e889cfd361d6b11f2029ca5570812d
enum EnumKey : String {
    case aKey = "Key A from Enum"
    case bKey = "Key B from Enum"
    case cKey = "Key C from Enum"
}

extension UserDefaults {
    // generics!
    func set<T>(_ value: T, forEnumKey enumKey: EnumKey) {
        set(value, forKey: enumKey.rawValue)
    }

    // you'd need one method per type, unfortunately, just like the original
    func bool(forEnumKey enumKey: EnumKey) -> Bool {
        return bool(forKey: enumKey.rawValue)
    }
    
    func object(forEnumKey enumKey: EnumKey) -> Any? {
        return self.object(forKey: enumKey.rawValue)
    }
}

class NamespaceEnums: XCTestCase {
    func testEnums() {
        UserDefaults.standard.set(true, forEnumKey: .aKey)

        let result = UserDefaults.standard.bool(forEnumKey: .aKey)
        XCTAssertTrue(result)

        let result2 = UserDefaults.standard.object(forEnumKey: .aKey)
        XCTAssertTrue(result2! as! Bool)
    }
}

Unfortunately, there's no way to get inheritance for Enums, otherwise this would be much better ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment