logo

Swift Platform Cocoapods GitHub release (latest SemVer) GitHub GitHub Workflow Status (with event)

一个基于 Swift 的轻量级框架,能够在预配置的存储中持久化 Swift 属性。

目录

功能亮点

基本用法

创建一个持久化的属性只需要在变量上方添加 @Persisted 属性包装器,指定用于反映存储中属性值的键,并为属性本身分配一个默认值。如果该属性是 Optional 并且没有提供默认值,则必须指定 nil

@Persisted(key: "myProperty")
var myProperty: Double = 10.0
@Persisted(key: "myOptionalProperty")
var myOptionalProperty: String? = nil // default value cannot be omitted

高级用法

可以自定义属性要持久化到的存储服务。PersistedProperty 提供对基于 UserDefaults 的存储和基于 KeyChain 的存储的原生支持。 您可以在属性上方添加 @Persisted 属性包装器时配置要使用的存储

// This will be persisted in the standard UserDefaults (same as omitting the storage parameter).
@Persisted(key: "myProperty", storage: .standard)
var myProperty: Double = 10.0
// This will be persisted in the iOS KeyChain.
@Persisted(key: "myPassword", storage: .keychain)
var myPassword: String? = nil

此外,您可以通过创建符合 StorageService 协议的存储提供程序来指定自定义存储服务

/// A custom storage provider conforming to the StorageService protocol
class MyCustomStorageService: StorageService {
    
    func load<ValueType>(key: String) -> ValueType? where ValueType: Codable ...
    
    func save<ValueType>(_ value: ValueType, key: String) where ValueType: Codable ...
    
    func remove(key: String) ...
    
}

let myService: StorageService = MyCustomStorageService()

// This will be persisted in the custom storage service.
@Persisted(key: "myProperty", storage: .custom(service: myService))
var myProperty: Double = 10.0

安装

Cocoapods

在您的 Podfile 中添加对 PersistedProperty 框架的依赖

pod 'PersistedProperty', '~> 1.1.0'

Swift Package Manager

将其作为 Swift Package 中的一个依赖项添加

dependencies: [
    .package(url: "https://github.com/danielepantaleone/PersistedProperty.git", .upToNextMajor(from: "1.1.0"))
]

贡献

如果您喜欢这个项目,可以通过以下方式贡献

许可证

MIT License

Copyright (c) 2023 Daniele Pantaleone

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.