How can I store a Swift enum value in NSUserDefaults

前端 未结 7 744
猫巷女王i
猫巷女王i 2021-01-31 07:47

I have an enum like this:

enum Environment {
    case Production
    case Staging
    case Dev
}

And I\'d like to save an instance in NSUserDef

7条回答
  •  情话喂你
    2021-01-31 08:09

    Using Codable protocol

    Extent Environment enum that conforms to Codable protocol to encode and decode values as Data.

    enum Environment: String, Codable {
        case Production
        case Staging
        case Dev
    }
    
    

    A wrapper for UserDefaults:

    struct UserDefaultsManager {
        static var userDefaults: UserDefaults = .standard
        
        static func set(_ value: T, forKey: String) where T: Encodable {
            if let encoded = try? JSONEncoder().encode(value) {
                userDefaults.set(encoded, forKey: forKey)
            }
        }
        
        static func get(forKey: String) -> T? where T: Decodable {
            guard let data = userDefaults.value(forKey: forKey) as? Data,
                let decodedData = try? JSONDecoder().decode(T.self, from: data)
                else { return nil }
            return decodedData
        }
    }
    

    Usage

    // Set
    let environment: Environment = .Production
    UserDefaultsManager.set(environment, forKey: "environment")
    
    // Get
    let environment: Environment? = UserDefaultsManager.get(forKey: "environment")
    
    

提交回复
热议问题