UserDefaultSugar is a Swift library that provides a simple and convenient way to work with UserDefaults. It includes extensions for UserDefaults that allow you to easily store and retrieve Codable objects, check if a key exists, and more.
To use UserDefaultSugar in your project, simply add the following line to your Package.swift
file:
`"github.com/eonist/UserDefaultSugar" branch: "master"`
Then, import the library in your Swift file:
import UserDefaultSugar
You can then use the various extensions provided by the library. For example, to print all data stored in UserDefaults, use:
UserDefaults.debug()
To remove all data stored in UserDefaults, use:
UserDefaults.removeAll()
To check if a key exists in UserDefaults, use:
let exists = UserDefaults.standard.exists(keyName: "myKey")
To store a Codable object in UserDefaults, use:
let myObject = MyObject()
UserDefaults.standard.set(object: myObject, forKey: "myKey")
To retrieve a Codable object from UserDefaults, use:
if let myObject = try? UserDefaults.standard.get(objectType: MyObject.self, forKey: "myKey") {
// Do something with myObject
}
struct Prefs: UserDefKind {
var allowTelemetry: Bool
var userName: String
}
extension Prefs {
static var defaultModel: Self {
.init{
allowTelemetry: true,
userName: "John Doe"
}
}
static var key: String { "app-name-prefs" }
}
let prefs = Prefs()
prefs.userName = "James" // writes to userdefault
prefs.allowTelemetry = false // writes to userdefault
http://eon.codes/blog/2018/09/18/userdefaults/
- SwiftyUserDefaults Another popular library for working with UserDefaults in Swift.
- Share UserDefault between app and extension See for more details: A Stack Overflow post that explains how to share UserDefaults between an app and its extensions.
- Blog post about using UserDefaults: A blog post that provides an overview of UserDefaults and how to use it in Swift.
- Make examples using UserDefKind
- Make headless xcodeproj?
- Add support for UserDefaults(suiteName: "group.your.bundle.here") etc
- Add Unit-tests 👈