Swift Package Index


A type safe extension to UserDefaults


  • The latest stable release is 1.0.0. Released 2 years ago.
  • The last commit to master was 2 years ago.

Swift Version Compatibility

  • 1.0.0 and master
    5.3
    5.2
    5.1
    5.0
    4.2
Full build results

Platform Compatibility

  • 1.0.0 and master
    iOS
    macOS(Intel)
    macOS(ARM)
    Linux
    tvOS
    watchOS
Full build results

Typesafe UserDefaults

Build Status

TypesafeUserDefaults is a thin extension to UserDefaults that enables a type safe use. As a bonus, types that conform to Codable can be stored in the UserDefaults.

Features

Strongly Typed

Define the keys:

enum UserKeys {
    static let name = UserDefaults.Key<String>("name")
    static let date = UserDefaults.Key<Date>("date")
}

Use them like the classic UserDefaults API:

UserDefaults.standard.set("Max Mustermann", forKey: UserKeys.name)
UserDefaults.standard.set(Date(), forKey: UserKeys.date)

let name = UserDefaults.standard.value(forKey: UserKeys.name)
let date = UserDefaults.standard.value(forKey: UserKeys.date)

Or use the convenient subscript:

UserDefaults.standard[UserKeys.name] = "Max Mustermann"
UserDefaults.standard[UserKeys.date] = Date()

let name = UserDefaults.standard[UserKeys.name]
let date = UserDefaults.standard[UserKeys.date]

The compiler will tell you if something is wrong:

// UIImage is not archivable in UserDefaults
let imageKey = UserDefaults.Key<UIImage>("image")

// Assigning value of type Date to a key that defined the value to be String
UserDefaults.standard[UserKeys.name] = Date()

// The return type does not match the type of the value
let date: Date = UserDefaults.standard[UserKeys.name]

Provide Default Values

Providing default values is simple as you define it in the same place with the key. No more need for using register

let pointsKey = UserDefaults.DefaultKey<Int>("points", 23)

var currentPoints = UserDefaults.standard[pointsKey] // 23
UserDefaults.standard[pointsKey] += 2
currentPoints = UserDefaults.standard[pointsKey] // 25

Store Codable Types

Conform to CustomDefaultsArchivable:

struct User: CustomDefaultsArchivable {
    let name: String
    let date: Date
}

Define the key:

let userKey = UserDefaults.Key<User>("user")

Use the key:

UserDefaults.standard[userKey] = User(name: "Max Mustermann", date: Date())
let name = UserDefaults.standard[userKey]?.name
let date = UserDefaults.standard[userKey]?.date

Requirements

>= Swift 4.1