你喜欢 Swift 的 Codable 协议,并在任何地方使用它
博士
你喜欢 Swift 的协议,并在任何地方使用它,谁不喜欢呢!这是一种简单而轻松的存储和检索方法 - 合理的数量?- 对象,在几行代码中!Codable
Codable
v2.0 简介
- 删除了协议以支持 Swift 的 .
Identifiable
Identifiable
- 增加了对 iOS、、 和 的部署目标。
13.0
tvOS 13.0
macOS 10.15
watchOS 6.0
- 定义为非最终类的对象现在也可以使用。
- 添加了新的和方法来生成和恢复可以保存(例如到iCloud)并在以后恢复的对象。
generateSnapshot()
restoreSnapshot(_:)
Snapshot
- 修复了可能与存储中对象的实际计数不同步的错误。
objectsCount
安装
Swift Package Manager (推荐)
You can use The Swift Package Manager to install by adding the proper description to your file:UserDefaultsStore
Package.swift
Next, add to your targets dependencies like so:UserDefaultsStore
Then run .swift package update
可可豆荚
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; and defined as bellow:User
Laptop
Here is how you store them in UserDefaultsStore:
1. Conform to the protocol and set the propertyIdentifiable
id
The protocol lets UserDefaultsStore knows what is the unique id for each object.Identifiable
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 , , , or any type.Int
Double
String
Codable
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.