How to save enum in UserDefaults using Swift

UserDefaults allow you to store small pieces of data of the following types: Data, String, Number, Date, Array or Dictionary. Enumerations are not supported by UserDefaults so it’s not possible to store them directly. We are going to leverage raw values of enums to save them in UserDefaults because a raw value can be a string, a character, or a value of any integer or floating-point type – data types that are supported by UserDefaults in Swift.

If you’d like to learn more about the basics of UserDefaults, then take a look at my introductory UserDefaults tutorial.

First, define an enum with raw values:

enum IconSize: String {
    case small = "small"
    case medium = "medium"
    case large = "large"
}

Then, get the standard user defaults object which we’re going to use in order to set and get the defaults:

let defaults = UserDefaults.standard

Save the raw value of an enum to UserDefaults:

var iconSize: IconSize = .medium
defaults.set(iconSize.rawValue, forKey: "iconSize")

Get a raw value from UserDefaults and create an instance of enum from it:

if let iconSizeRawValue = defaults.object(forKey: "iconSize") as? String {
    let iconSize = IconSize(rawValue: iconSizeRawValue)!
}

Related tutorials: