Skip to content

A property wrapper to save `Codable` objects to UserDefaults

License

Notifications You must be signed in to change notification settings

mrgrauel/UserDefaultsBacked

Repository files navigation

UserDefaultsBacked

badge-mit badge-languages badge-pms badge-platforms

A property wrapper to save Codable objects in UserDefaults.
Inspired by https://www.swiftbysundell.com/articles/property-wrappers-in-swift/.

Getting Started

We only support Swift Package Manager

Swift Package Manager

.package(url: "https://github.com/mrgrauel/UserDefaultsBacked.git", from: "1.0.0")

Example

@UserDefaultsBacked("sample", defaultValue: false)
var sample: Bool

@UserDefaultsBacked("sampleString", defaultValue: "sample")
var sampleString: String

// MARK: `nil` Support

@UserDefaultsBacked("nil_check")
var nilSample: String?

// MARK: Custom `UserDefaults`

static var userDefaults = UserDefaults(suiteName: "StorageTests")!

@UserDefaultsBacked("other_defaults", defaultValue: true, userDefaults: userDefaults)
var otherDefaults: Bool

// MARK: Custom `Codable`

enum Environment: String, Codable {
    case development, stage, production
}

@UserDefaultsBacked("environment", defaultValue: .production)
var environment: Environment

struct Mock: Codable {
    let value: Int
}

@UserDefaultsBacked("codable")
var codable: Mock?