Swiftpack.co - Package - S2Ler/Preferences


swift platform spm carthage compatible

Preferences is Simple, Extensible, Strongly Typed UserDefaults/Keychain/[Put Yours] for iOS, macOS, tvOS (macOS, tvOS support comming soon).


Instantiate your variant of preferences:

let preferences = KeychainPreferences() // or UserDefaults.standard

Define Key

With AnyPreferenceKey:

let key = AnyPreferenceKey<String>(rawKey: "aKey")

With custom key conforming to protocol PreferenceKey:

struct AddressKey: PreferenceKey {
    let name: String

    typealias PreferenceValueType = String
    var rawKey: String { return name }

let key = AddressKey(name: "aKey")

PreferenceKey have an assosiated type which should conform to Codable protocol. You can save to preferences anything that conforms to Codable including String, Date, Int, etc.

Set Value

Set a value with AnyPreferenceKey:

try preferences.set("PreferenceValue", for: key)

Get Value

let value: String? = try preferences.get(key)

Remove Value

try preferences.set(nil, for: key)

Complex example

Define value:

struct Name: Codable {
  let first: String
  let second: String

Define key:

struct NameKey: PreferenceKey {
  let name: String

  typealias PreferenceValueType = Name
  var rawKey: String { return name }


let preferences = KeychainPreferences()

let myName = Name(first: "Alex", second: "B")
let currentUserKey = NameKey(name: "com.app.current_user")

do {
    try preferences.set(myName, for: currentUserKey)
    let savedValue: Name? = try preferences.get(currentUserKey)
    print("Saved value: \(String(describing: savedValue))")
catch {
    print("Can't save value with error: \(error)")

Custom Preferences

  • Step 1: Create a type that conforms to Preferences.
  • Step 2: Use 🙂
  • Step 3: Submit pull request, so that I can consider including your preferences in a standard bundle if it makes sense.



Stars: 0



Swift 5 - 2020-08-31 10:53:05

0.1.0 - 2017-09-06 14:59:35


  • Replace PreferenceValue protocol with Swift 4 Codable protocol
  • AnyPreferenceKey to simplify creation of the keys.
  • SPM support