Can a nested enum be saved inside UserDefaults?

2019-07-22 15:38发布

问题:

Let's say I have the following enums:

enum UserState {
    case LoggedIn(LoggedInState)
    case LoggedOut(LoggedOutState)
}

enum LoggedInState {
    case Playing
    case Paused
    case Stopped
}

enum LoggedOutState {
    case Unregistered
    case Registered
}

Is there a way to save UserState to UserDefaults ?

回答1:

Yes

You can use Codable protocol to transform your enum into a representation that can be saved in UserDefaults. This tutorial might give you a kickstart.