简体   繁体   中英

Swift enum, get raw value from associated enum

I wanted to make an enum which would carry all the UserDefaults keys in my app.

enum UserDefaultsKeys: String {
 case isLoggedIn
 case rememberLoginEmail 
}

At the same time I wanted it to be categorised as well so that one enum does not have too many keys from different modules, so I did this:

enum UserDefaultsKeys {
    case session(key: UserSessionKeys)
    case userPreference(key: UserPreferenceKeys)

    func key() -> String{
        switch self {

        case .session(let key):
            return key.rawValue

        case .userPreference(let key):
            return key.rawValue
        }
    }
}

enum UserSessionKeys: String {
    case isLoggedIn
}

enum UserPreferenceKeys: String {
    case rememberLoginEmail
}

I can access the raw value now by this: UserDefaultsKeys.session(key: .isLoggedIn).key()

It seems that I had to write a whole another function to get the raw value from an associated enum type. I feel there could be a better way for this, any suggestions?

One way to do this is to mix enum with static constants

enum UserDefaultsKeys {
    enum Session {
        static let isLoggedIn = "key1"
        static let ...
    }

    enum Preferences {
        static let rememberLoginEmail = "key2"
    }
}

and then access them via their paths

let isLoggedInKey = UserDefaultsKeys.Session.isLoggedIn

I suggest using such a solution

 enum UserDefaultsKeys {
        case abstractContainer(key: KeyContainer)

        var key: String {
            switch self {
            case .abstractContainer(let key):
                return key.rawValue
            }
        }
    }
    protocol KeyContainer {
        var rawValue: String { get }
    }

enum UserSessionKeys: String, KeyContainer {
    case isLoggedIn
}

enum UserPreferenceKeys: String, KeyContainer {
    case rememberLoginEmail
}

let u = UserDefaultsKeys.abstractContainer(key: UserSessionKeys.isLoggedIn)
print(u.key)

use only one abstract case and protocol instead of several items

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM