DefaultsKit is a Swift package that provides a clean and type-safe way to manage UserDefaults keys and values. It introduces extensible protocols for keys and convenient property wrappers for storing, retrieving, and managing preferences using a consistent prefix strategy.
- Type-safe
UserDefaultsKeys: Use enums conforming toUserDefaultsKeyRepresentableto define keys with automatic prefix handling. - Property Wrappers:
@DefaultsPersisted: A powerful property wrapper for anyCodabletype with built-in support for primitives and optionals@AppStorage:Enhanced SwiftUI integration with type-safe keys for common types
- Prefix Management: Supports internal bundle identifiers or custom prefixes via the
UserDefaultsKeyRepresentableprotocol. - Utility Functions: Includes methods for setting, getting, printing, and deleting
UserDefaultsentries CodableSupport: Automatic encoding/decoding for complex types
Add DefaultsKit to your Swift project using Swift Package Manager.
dependencies: [
.package(url: "https://github.com/markbattistella/DefaultsKit", from: "1.0.0")
]Define keys by conforming your enums to UserDefaultsKeyRepresentable:
enum UserDefaultsKey: String, UserDefaultsKeyRepresentable {
case userPreference
case appTheme
case userProfile
}The @DefaultsPersisted property wrapper supports any Codable type:
// For primitive types
@DefaultsPersisted(UserDefaultsKey.userPreference)
var isEnabled: Bool = false
// For custom types
@DefaultsPersisted(UserDefaultsKey.userProfile)
var profile: UserProfile = UserProfile(name: "John", age: 30)
// For optional values
@DefaultsPersisted(UserDefaultsKey.lastLoginDate)
var lastLogin: Date?Use type-safe keys with SwiftUI's @AppStorage:
struct ContentView: View {
@AppStorage(UserDefaultsKey.userPreference)
var isEnabled: Bool = false
var body: some View {
Toggle("Enable Feature", isOn: $isEnabled)
}
}Use the extended UserDefaults methods:
// Setting values
UserDefaults.standard.set(true, for: UserDefaultsKey.userPreference)
// Getting values
let preference = UserDefaults.standard.bool(for: UserDefaultsKey.userPreference)
// Encoding complex objects
try? UserDefaults.standard.encode(profile, for: UserDefaultsKey.userProfile)
// Decoding complex objects
let savedProfile: UserProfile? = try? UserDefaults.standard.decode(for: UserDefaultsKey.userProfile)// Register defaults
UserDefaults.standard.register(
defaults: [
UserDefaultsKey.appTheme: "light",
UserDefaultsKey.userPreference: true
]
)// Print all values from the UserDefaultsKey enum
UserDefaults.printAllKeys(from: UserDefaultsKey.self)
// Delete all values in the UserDefaultsKey enum
UserDefaults.deleteAllKeys(from: UserDefaultsKey.self)Using it this way allows you to segregate different UserDefaultsKeyRepresentable enums, and print or delete them.
DefaultsKit is available under the MIT license. See the LICENSE file for more information.