{"id":18060637,"url":"https://github.com/0xleif/cache","last_synced_at":"2025-04-11T12:23:12.277Z","repository":{"id":174011303,"uuid":"651653090","full_name":"0xLeif/Cache","owner":"0xLeif","description":"📦 A simple, lightweight caching library for Swift.","archived":false,"fork":false,"pushed_at":"2024-09-27T18:20:25.000Z","size":59,"stargazers_count":6,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-03T10:19:00.775Z","etag":null,"topics":["cache","data","dictionary","ios","json","linux","lru-cache","macos","memory","property-wrappers","swift","tvos","watchos","windows"],"latest_commit_sha":null,"homepage":"https://0xleif.github.io/Cache/","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/0xLeif.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2023-06-09T18:22:18.000Z","updated_at":"2024-09-27T18:18:48.000Z","dependencies_parsed_at":"2023-11-12T01:31:54.386Z","dependency_job_id":"824ebc0d-f423-42a8-b10a-a916b7ad309b","html_url":"https://github.com/0xLeif/Cache","commit_stats":null,"previous_names":["0xleif/cache"],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/0xLeif%2FCache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/0xLeif%2FCache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/0xLeif%2FCache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/0xLeif%2FCache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/0xLeif","download_url":"https://codeload.github.com/0xLeif/Cache/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248401319,"owners_count":21097328,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cache","data","dictionary","ios","json","linux","lru-cache","macos","memory","property-wrappers","swift","tvos","watchos","windows"],"created_at":"2024-10-31T04:10:01.064Z","updated_at":"2025-04-11T12:23:12.241Z","avatar_url":"https://github.com/0xLeif.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Cache\n\n*A simple, lightweight caching library for Swift.*\n\n## What is Cache?\n\nCache is a Swift library for caching arbitrary data types in memory. It provides a simple and intuitive API for storing, retrieving, and removing objects from the cache.\n\n## Features\n\n- Generic value type\n- Supports JSON serialization and deserialization\n- Flexible caching, allowing for multiple Cache objects with different configurations\n- Thread-safe implementation\n- Property Wrappers\n\n## Installation\n\n### Swift Package Manager (SPM)\n\nAdd the following line to your `Package.swift` file in the dependencies array:\n\n```swift\ndependencies: [\n    .package(url: \"https://github.com/0xLeif/Cache.git\", from: \"2.0.0\")\n]\n```\n\n## Usage\n\n### Basic Usage\n\nFirst, import the `Cache` module:\n\n```swift\nimport Cache\n```\n\nCreate a cache instance with a generic key-value pair:\n\n```swift\nlet cache = Cache\u003cCacheKey, String\u003e()\n```\n\nAdd values to the cache using a key-value syntax:\n\n```swift\ncache[.text] = \"Hello, World!\"\n```\n\nRetrieve values using the same key-value syntax:\n\n```swift\nlet cachedValue = cache[.text]\n```\n\n### Multiple Cache Objects\n\nYou can create multiple `Cache` objects by specifying a different type of key-value pair:\n\n```swift\nlet cache1 = Cache\u003cCacheKey, String\u003e()\nlet imageCache = Cache\u003cURL, UIImage\u003e()\n```\n\n### Using JSON\n\nYou can use `JSON` to parse and serialize JSON data in the cache:\n\n```swift\nlet json: JSON\u003cCacheKey\u003e = JSON(data: jsonData)\n```\n\n### Removing Values\n\nYou can remove values from the cache using the `remove` method:\n\n```swift\ncache.remove(.text)\n```\n\nYou can also just set the value to `nil` using the subscripts\n\n```swift\ncache[.text] = nil\n```\n\n### ExpiringCache\n\nThe `ExpiringCache` class is a cache that retains and returns objects for a specific duration set by the `ExpirationDuration` enumeration. Objects stored in the cache are automatically removed when their expiration duration has passed.\n\n#### Usage\n\n```swift\n// Create an instance of the cache with a duration of 5 minutes\nlet cache = ExpiringCache\u003cString, Int\u003e(duration: .minutes(5))\n\n// Store a value in the cache with a key\ncache[\"Answer\"] = 42\n\n// Retrieve a value from the cache using its key\nif let answer = cache[\"Answer\"] {\n    print(\"The answer is \\(answer)\")\n}\n```\n\n#### Expiration Duration\n\nThe expiration duration of the cache can be set with the `ExpirationDuration` enumeration, which has three cases: `seconds`, `minutes`, and `hours`. Each case takes a single `UInt` argument to represent the duration of that time unit.\n\n### PersistableCache\n\nThe `PersistableCache` class is a cache that stores its contents persistently on disk using a JSON file. Use it to create a cache that persists its contents between application launches. The cache contents are automatically loaded from disk when initialized, and can be saved manually whenever required.\n\nTo use `PersistableCache`, make sure that the specified key type conforms to both `RawRepresentable` and `Hashable` protocols. The `RawValue` of `Key` must be a `String` type.\n\n Here's an example of creating a cache, setting a value, and saving it to disk:\n\n ```swift\n enum Key: String {\n     case pi\n }\n \n let cache = PersistableCache\u003cKey, Double, Double\u003e()\n\n cache[.pi] = Double.pi\n\n do {\n     try cache.save()\n } catch {\n     print(\"Failed to save cache: \\(error)\")\n }\n ```\n\n You can also load a previously saved cache from disk:\n\n ```swift\n let cache = PersistableCache\u003cKey, Double, Double\u003e()\n\n let pi = cache[.pi] // pi == Double.pi\n ```\n \n Remember that the `save()` function may throw errors if the encoder fails to serialize the cache to JSON or the disk write operation fails. Make sure to handle the errors appropriately.\n\n### Advanced Usage\n\nYou can use `Cache` as an observed object:\n\n```swift\nstruct ExampleView: View {\n    enum Key {\n        case title\n    }\n\n    @ObservedObject var cache = Cache\u003cKey, String\u003e()\n\n    var body: some View {\n        TextField(\n            \"Cache Title\",\n            text: $cache[.title, default: \"\"]\n        )\n    }\n}\n```\n\n## Cacheable Functions\n\n`Cacheable` protocol defines the following functions which can be used to work with the Cache or JSON.\n\n#### allValues\n\n`allValues` property returns a dictionary containing all the key-value pairs stored in the cache.\n\n```swift\nvar allValues: [Key: Value] { get }\n```\n\n#### init\n\nThe `init` function initializes the cache instance with an optional dictionary of key-value pairs.\n\n```swift\ninit(initialValues: [Key: Value])\n```\n\n#### get\n\nThe get function retrieves the value of the specified key and casts it to a given output type (if possible).\n\n```swift\nfunc get\u003cOutput\u003e(_ key: Key, as: Output.Type) -\u003e Output?\n```\n\nAlternatively, calling get with only the key returns the value casted to the default Value type.\n\n```swift\nfunc get(_ key: Key) -\u003e Value?\n```\n\n#### resolve\n\nThe resolve function retrieves the value of the specified key and casts it to a given output type, but throws an error if the specified key is missing or if the value cannot be casted to the given output type.\n\n```swift\nfunc resolve\u003cOutput\u003e(_ key: Key, as: Output.Type) throws -\u003e Output\n```\n\nAlternatively, calling resolve with only the key casts the value to the default Value type.\n\n```swift\nfunc resolve(_ key: Key) throws -\u003e Value\n```\n\n#### set\n\nThe set method sets the specified value for the specified key in the cache.\n\n```swift\nfunc set(value: Value, forKey key: Key)\n```\n\n#### remove\n\nThe remove method removes the value of the specified key from the cache.\n\n```swift\nfunc remove(_ key: Key)\n```\n\n#### contains\n\nThe contains method returns a Boolean indicating whether the cache contains the specified key.\n\n```swift\nfunc contains(_ key: Key) -\u003e Bool\n```\n\n#### require\n\nThe require function ensures that the cache contains the specified key or keys, or else it throws an error.\n\n```swift\nfunc require(_ key: Key) throws -\u003e Self\n```\n\n```swift\nfunc require(keys: Set\u003cKey\u003e) throws -\u003e Self\n```\n\n#### values\n\nThe values function returns a dictionary containing only the key-value pairs where the value is of the specified output type.\n\n```swift\nfunc values\u003cOutput\u003e(ofType: Output.Type) -\u003e [Key: Output]\n```\n\nThe default value for ofType parameter is Value.\n\n## Contributing\n\nIf you have improvements or issues, feel free to open an issue or pull request!\n\n## License\n\nCache is released under the MIT License. See `LICENSE` for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F0xleif%2Fcache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F0xleif%2Fcache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F0xleif%2Fcache/lists"}