PropertyDefaults 1.0

PropertyDefaults 1.0

Taeho Lee 维护。



  • Taeho Lee

PropertyDefaults

cocoapods compatible carthage compatible language swift

PropertyDefaults 是一个简单的 UserDefaults 包装器,它让您保证不安全的基于字面值的 UserDefaults 的键和值,并保证它们。支持 Codable 类型。本项目是以区别于 DefaultsKit 的完全不同的方法进行重合的项目。

安装

安装指南

使用

实例化或获取 sharedDefaults 实例

let defaults = Defaults() // or Defaults.shared

特性

  • Swift 4 Codable 支持
  • 键值类型安全性 - 使用预定义的 Swift 属性而不是字符串字面值。
  • 限制仅使用协议。
  • 使用协议进行权限控制。
  • 与 Keychain Access 以相同接口集成。

键安全属性定义

PropertyDefaults 只支持协议扩展模式,该模式专注于语法驱动的键值处理,因此与 Swift 相结合使用时,可以完美地使用自定义属性。

这是使用基本 Codable 类型的一个示例

extension Defaults: PropertyDefaults {
    public var autoStringProperty: String? {
        set{ set(newValue) } get{ return get() }
    }
    public var autoDateProperty: Date? {
        set{ set(newValue) } get{ return get() }
    }
}

因此,您可以像这样使用 Defaults

var sharedDefaults = Defaults()
sharedDefaults.autoStringProperty = "the new value will persist in shared scope"
Defaults.shared.autoStringProperty = "the new value will persist in shared scope"

// sharedDefaults.autoStringProperty == Defaults.shared.autoStringProperty

var localDefaults = Defaults(suiteName:"local")
localDefaults.autoStringProperty = "the new value will persist in local scope"

// localDefaults.autoStringProperty != Defaults.shared.autoStringProperty

直接以 Codable 类型保存/加载

public struct CustomValueType: Codable{
    var key:String = "value"
}
extension Defaults: PropertyDefaults {
    // default value with 'or'
    public var autoStringPropertyWithDefaultValue: String? {
        set{ set(newValue) } get{ return get(or:"default string value") }
    }
    // non-optional - must define the default value with the keyword 'or'
    public var autoCustomNonOptionalProperty: CustomValueType {
        set{ set(newValue) } get{ return get(or: CustomValueType()) }
    }
    // optional with/without setter default value
    public var autoCustomOptionalProperty: CustomValueType? {
        set{ set(newValue) } get{ return get() }
    }
    public var autoCustomOptionalPropertySetterDefaultValue: CustomValueType? {
        set{ set(newValue, or: CustomValueType()) } get{ return get() }
    }
}

使用此模式,正如您所知,您也可以使用协议控制访问权限。这意味着您可以使用 'private' 或 'fileprivate' defaults 访问。

// MyFile.swift
fileprivate protocol PrivateDefaultKeysInThisSwiftFile:PropertyDefaults{
    var filePrivateValue: String? {set get}
}

extension Defaults: PrivateDefaultKeysInThisSwiftFile {
    public var filePrivateValue: String? {
        set{ set(newValue) } get{ return get() }
    }
}

// Can access - 👌
Defaults.shared.filePrivateValue
// MyOtherFile.swift

// Not able to access - ❌
Defaults.shared.filePrivateValue