Swiftpack.co - S2Ler/Preferences as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by S2Ler.
S2Ler/Preferences 0.3.1
Simple, Extensible, Strongly Typed UserDefaults/Keychain/[Put Yours] for iOS, macOS, tvOS.
⭐️ 0
🕓 3 years ago
.package(url: "https://github.com/S2Ler/Preferences.git", from: "0.3.1")

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).

Usage

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 }
}

Use:

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.

Links

GitHub

link
Stars: 0
Last commit: 1 year ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Release Notes

Swift 5
3 years ago

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics