How do I persist enum cases with raw values?

In Swift, you can persist enum cases with raw values using the `UserDefaults` system or by archiving the enum values. This can be particularly useful when you want to save user preferences or application state. Below is an example of how to do this in Swift.

enum UserPreference: String { case darkMode = "darkMode" case lightMode = "lightMode" } // Save the selected preference func savePreference(_ preference: UserPreference) { UserDefaults.standard.set(preference.rawValue, forKey: "userPreference") } // Load the saved preference func loadPreference() -> UserPreference? { if let savedPreference = UserDefaults.standard.string(forKey: "userPreference") { return UserPreference(rawValue: savedPreference) } return nil } // Example usage savePreference(.darkMode) if let preference = loadPreference() { print("Current preference: \(preference.rawValue)") }

Swift enums raw values persist enum cases UserDefaults Swift programming save user preferences