Easy to use UserDefaults for iOS apps.
Defaults.swift is a easy-to-use generic interface built on top of UserDefaults
in Swift.
- Compile time checks by using generics
- Swifty syntax
- Easy to use
- Fully extendable
- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+
- Xcode 8.0+
- Swift 3.0+
CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:
$ gem install cocoapods
CocoaPods 1.1.0+ is required to build Defaults.swift 1.0.0+.
To integrate Defaults.swift into your Xcode project using CocoaPods, specify it in your Podfile
:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!
target '<Your Target Name>' do
pod 'Defaults.swift', '~> 2.0'
end
Then, run the following command:
$ pod install
Defaults.swift
provides the user two different interfaces.
Defaults.swift
uses a structure called DefaultKey<T>
to handle the UserDefaults
keys.
let defaultKey = DefaultKey<String>("key")
// Get the string value for the key. The method returns an Optional
let storedString = UserDefaults.standard.get(for: defaultKey)
// Store a new value
UserDefaults.standard.set("hello", for: defaultKey)
Here is the power of Defaults.swift
: you can't store different types for the same key
UserDefaults.standard.set(10, for: defaultKey) // this won't compile
// Delete the value from the storage
UserDefaults.standard.set(nil, for: defaultKey)
// or by calling
UserDefaults.standard.removeValue(for: defaultKey)
The DefaultKey
structure is now generic. Before you declared
let key = DefaultKey.Name(rawValue: "YOUR_KEY")!
Now, for a more type safety, you have to declare the type the key should hold.
The internal struct Name
doesn't exist anymore
let key = DefaultKey<String>("YOUR_KEY")
If you want to display, somehow, the key name in your code, you can replace
let key = yourDefaultKeyName.rawValue
to:
let key = yourDefaultKey.name
You can still compare two differents key by using the ==
operator.
Pay attention that the application won't compile if you're going to compare two
DefaultKey
with different generic type. For example
let key = DefaultKey<String>("key")
let aKey = DefaultKey<Int>("key")
let otherKey = DefaultKey<String>("a")
let anotherKey = key
key == aKey // this won't compile because they hold different types
key == otherKey // this will return false because the name is different
key == anotherKey // this will return true
Defaults.swift is released under the MIT license. See LICENSE for details.