Swiftpack.co - nearfri/UserDefaultsWrapper as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by nearfri.
nearfri/UserDefaultsWrapper 0.9.1
A Swift library that makes it easy to use UserDefaults.
⭐️ 0
🕓 22 hours ago
iOS macOS watchOS tvOS
.package(url: "https://github.com/nearfri/UserDefaultsWrapper.git", from: "0.9.1")



A Swift library that makes it easy to use UserDefaults.


import UserDefaultsWrapper

enum ColorType: String, Codable {
    case red
    case blue
    case green
    case black
    case white

// 1. Define preferences class that inherits `KeyValueStoreCoordinator`.
// 2. Add properties with property wrapper `@Stored`.
final class Preferences: KeyValueStoreCoordinator {
    var intNum: Int = 3
    var optIntNum: Int?
    var str: String = "hello"
    var secretText: String = "encrypted information"
    var rect: CGRect = CGRect(x: 1, y: 2, width: 3, height: 4)
    var colors: [ColorType] = [.blue, .black, .green]
    var dataModificationDate: Date?
    static let standard: Preferences = .init(
        store: UserDefaultsStore(
            defaults: .standard,
            valueCoder: CryptoValueCoderDecorator( // Encrypt using ChaChaPoly
                valueCoder: JSONValueCoder(),
                symmetricKey: KeyChain.someSymmetricKey,
                encryptWhere: { $0.hasPrefix("encrypted_") })))
    static let inMemory: Preferences = .init(store: InMemoryStore())

// 3. Just use it.
let preferences = Preferences.standard

preferences.intNum = 5
assert(preferences.intNum == 5)
assert(UserDefaults.standard.integer(forKey: "intNum") == 5)

preferences.rect.size = CGSize(width: 5, height: 6)
assert(preferences.rect.size == CGSize(width: 5, height: 6))

preferences.$rect.sink { print("\($0)") }

// 4. Add `KeyValueLookup` conformance for more features.
extension Preferences: KeyValueLookup {}

preferences.removeStoredValue(for: \.intNum)
assert(UserDefaults.standard.object(forKey: "intNum") == nil)
assert(preferences.intNum == 3) // Default value

For more example usage, see the sample app in Samples folder.


Swift Package Manager

.package(url: "https://github.com/nearfri/UserDefaultsWrapper", from: "0.9.0")


Preferences is released under the MIT license. See LICENSE for more information.


Stars: 0
Last commit: Yesterday
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.

Release Notes


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