缓存

一个简单、轻量级的 Swift 缓存库。

什么是 Cache?

Cache 是一个 Swift 库,用于在内存中缓存任意数据类型。 它提供了一个简单直观的 API,用于存储、检索和删除缓存中的对象。

特性

安装

Swift 包管理器 (SPM)

将以下行添加到您的 Package.swift 文件中的 dependencies 数组中

dependencies: [
    .package(url: "https://github.com/0xLeif/Cache.git", from: "2.0.0")
]

用法

基本用法

首先,导入 Cache 模块

import Cache

使用泛型键值对创建一个缓存实例

let cache = Cache<CacheKey, String>()

使用键值语法向缓存添加值

cache[.text] = "Hello, World!"

使用相同的键值语法检索值

let cachedValue = cache[.text]

多个 Cache 对象

您可以通过指定不同类型的键值对来创建多个 Cache 对象

let cache1 = Cache<CacheKey, String>()
let imageCache = Cache<URL, UIImage>()

使用 JSON

您可以使用 JSON 在缓存中解析和序列化 JSON 数据

let json: JSON<CacheKey> = JSON(data: jsonData)

移除值

您可以使用 remove 方法从缓存中移除值

cache.remove(.text)

您也可以使用下标将值设置为 nil

cache[.text] = nil

ExpiringCache

ExpiringCache 类是一个缓存,它保留对象并在 ExpirationDuration 枚举设置的特定持续时间内返回对象。 存储在缓存中的对象会在其过期持续时间过后自动删除。

用法

// Create an instance of the cache with a duration of 5 minutes
let cache = ExpiringCache<String, Int>(duration: .minutes(5))

// Store a value in the cache with a key
cache["Answer"] = 42

// Retrieve a value from the cache using its key
if let answer = cache["Answer"] {
    print("The answer is \(answer)")
}

过期时间

缓存的过期时间可以使用 ExpirationDuration 枚举设置,它有三种情况:secondsminuteshours。 每种情况都接受一个 UInt 参数来表示该时间单位的持续时间。

PersistableCache

PersistableCache 类是一个缓存,它使用 JSON 文件将其内容持久地存储在磁盘上。 使用它创建一个在应用程序启动之间保持其内容的缓存。 缓存内容在初始化时自动从磁盘加载,并且可以根据需要在任何时候手动保存。

要使用 PersistableCache,请确保指定的键类型符合 RawRepresentableHashable 协议。 KeyRawValue 必须是 String 类型。

这是一个创建缓存、设置值并将其保存到磁盘的示例

enum Key: String {
    case pi
}

let cache = PersistableCache<Key, Double, Double>()

cache[.pi] = Double.pi

do {
    try cache.save()
} catch {
    print("Failed to save cache: \(error)")
}

您还可以从磁盘加载先前保存的缓存

let cache = PersistableCache<Key, Double, Double>()

let pi = cache[.pi] // pi == Double.pi

请记住,如果编码器无法将缓存序列化为 JSON 或磁盘写入操作失败,则 save() 函数可能会抛出错误。 确保适当处理错误。

高级用法

您可以将 Cache 用作观察到的对象

struct ExampleView: View {
    enum Key {
        case title
    }

    @ObservedObject var cache = Cache<Key, String>()

    var body: some View {
        TextField(
            "Cache Title",
            text: $cache[.title, default: ""]
        )
    }
}

Cacheable 函数

Cacheable 协议定义了以下函数,可用于处理 Cache 或 JSON。

allValues

allValues 属性返回一个包含存储在缓存中的所有键值对的字典。

var allValues: [Key: Value] { get }

init

init 函数使用一个可选的键值对字典初始化缓存实例。

init(initialValues: [Key: Value])

get

get 函数检索指定键的值并将其转换为给定的输出类型(如果可能)。

func get<Output>(_ key: Key, as: Output.Type) -> Output?

或者,仅使用键调用 get 会返回转换为默认 Value 类型的值。

func get(_ key: Key) -> Value?

resolve

resolve 函数检索指定键的值并将其转换为给定的输出类型,但如果指定的键丢失或者该值无法转换为给定的输出类型,则会抛出错误。

func resolve<Output>(_ key: Key, as: Output.Type) throws -> Output

或者,仅使用键调用 resolve 会将该值转换为默认 Value 类型。

func resolve(_ key: Key) throws -> Value

set

set 方法在缓存中为指定的键设置指定的值。

func set(value: Value, forKey key: Key)

remove

remove 方法从缓存中删除指定键的值。

func remove(_ key: Key)

contains

contains 方法返回一个 Boolean 值,指示缓存是否包含指定的键。

func contains(_ key: Key) -> Bool

require

require 函数确保缓存包含指定的键或键,否则会抛出错误。

func require(_ key: Key) throws -> Self
func require(keys: Set<Key>) throws -> Self

values

values 函数返回一个仅包含值为指定输出类型的键值对的字典。

func values<Output>(ofType: Output.Type) -> [Key: Output]

ofType 参数的默认值为 Value。

贡献

如果您有改进或问题,请随时打开一个 issue 或 pull request!

许可证

Cache 在 MIT 许可证下发布。 有关详细信息,请参阅 LICENSE