tl;dr
You love Swift's Codable
protocol and use it everywhere, who doesn't! Here is an easy and very light way to store and retrieve -reasonable amount ?- of Codable
objects, in a couple lines of code!
Introducing v2.0
- Removed the
Identifiable
protocol in favor of Swift'sIdentifiable
. - Increased deployment targets to iOS
13.0
,tvOS 13.0
,macOS 10.15
, andwatchOS 6.0
. - Objects defined as non-final classes can now be used as well.
- Added new
generateSnapshot()
andrestoreSnapshot(_:)
methods to generate and restore aSnapshot
object that can be saved (e.g. to iCloud) and restored later. - Fixed a bug where
objectsCount
might run out of sync with the actual count of objects in store.
Installation
Swift Package Manager (Recommended)
You can use The Swift Package Manager to install UserDefaultsStore
by adding the proper description to your Package.swift
file:
Next, add UserDefaultsStore
to your targets dependencies like so:
Then run swift package update
.
CocoaPods
To integrate UserDefaultsStore into your Xcode project using CocoaPods, specify it in your Podfile
:
Carthage
To integrate UserDefaultsStore into your Xcode project using Carthage, specify it in your Cartfile
:
Usage
Let's say you have 2 structs; User
and Laptop
defined as bellow:
Here is how you store them in UserDefaultsStore:
1. Conform to the Identifiable
protocol and set the id
property
The Identifiable
protocol lets UserDefaultsStore knows what is the unique id for each object.
2. Create UserDefaults Stores
3. VoilĂ , you're all set!
Looking to store a single item only?
Use SingleUserDefaultsStore
, it enables storing and retrieving a single value of Int
, Double
, String
, or any Codable
type.
Requirements
- iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 6.0+
- Swift 5.0+
Thanks
Special thanks to:
- Paul Hudson for his article on how to use Swift keypaths to write more natural code.
- Batuhan Saka for translating this document into Turkish.
Credits
Icon made by freepik from flaticon.com.
License
UserDefaultsStore is released under the MIT license. See LICENSE for more information.