测试已测试 | ✗ |
语言语言 | SwiftSwift |
许可证 | MIT |
发布最新发布 | 2016年11月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✗ |
由 dalu93 维护。
易于使用的 iOS 应用程序的 UserDefaults。
Defaults.swift 是一个在 Swift 中基于 UserDefaults
的易于使用的通用接口。
Defaults.swift
为用户提供了两种不同的接口。
Defaults.swift
使用名为 DefaultKey<T>
的结构来处理 UserDefaults
密钥。
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)
这里是 Defaults.swift
强大的地方:您无法对同一密钥存储不同类型的值
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)
DefaultKey
结构现在是泛型的。在您声明之前:
let key = DefaultKey.Name(rawValue: "YOUR_KEY")!
现在,为了提高类型安全性,您必须声明密钥应持有的类型。内部结构 Name
不再存在。
let key = DefaultKey<String>("YOUR_KEY")
如果您想以某种方式在代码中显示键名,您可以替换
let key = yourDefaultKeyName.rawValue
到
let key = yourDefaultKey.name
您仍然可以使用 ==
运算符来比较两个不同的键。注意,如果您打算比较两个具有不同泛型类型的 DefaultKey
,则应用程序将无法编译。例如
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 在 MIT 许可下发布。请参阅 LICENSE 文件以获取详细信息。