Defaults.swift 2.1.0

Defaults.swift 2.1.0

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布最新发布2016年11月
SwiftSwift 版本3.0
SPM支持 SPM

dalu93 维护。



Defaults.swift

易于使用的 iOS 应用程序的 UserDefaults。

BuddyBuild

Defaults.swift 是一个在 Swift 中基于 UserDefaults 的易于使用的通用接口。

功能

  • [x] 使用泛型进行编译时间检查
  • [x] Swift 语法
  • [x] 易于使用
  • [x] 可完全扩展

要求

  • iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 8.0+
  • Swift 3.0+

用法

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)

迁移

从 1.x 迁移到 2.0.0

编译修复

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 文件以获取详细信息。