https://github.com/binaryscraping/swift-cache
A type-safe swifty wrapper around NSCache.
https://github.com/binaryscraping/swift-cache
cache nscache swift type-safe
Last synced: 11 months ago
JSON representation
A type-safe swifty wrapper around NSCache.
- Host: GitHub
- URL: https://github.com/binaryscraping/swift-cache
- Owner: binaryscraping
- License: mit
- Created: 2022-05-13T11:03:23.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2022-05-13T14:14:15.000Z (over 3 years ago)
- Last Synced: 2025-02-16T02:15:48.668Z (12 months ago)
- Topics: cache, nscache, swift, type-safe
- Language: Swift
- Homepage:
- Size: 11.7 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# swift-cache
[](https://swiftpackageindex.com/binaryscraping/swift-cache)
[](https://swiftpackageindex.com/binaryscraping/swift-cache)
A type-safe swifty wrapper around [`NSCache`](https://developer.apple.com/documentation/foundation/nscache).
## Getting Started
Add `swift-cache` as a dependency to your project using SPM.
```swift
.package(url: "https://github.com/binaryscraping/swift-cache", from: "0.1.0"),
```
And in your application/target, add `"Cache"` to your `"dependencies"`.
```swift
.target(
name: "YourTarget",
dependencies: [
.product(name: "Cache", package: "swift-cache"),
]
)
```
## Usage
`Cache` is accessed through a `Cache.Key` type, so start by defining your keys.
```swift
extension Cache.Key where Value == String {
// A key that stores a string value.
static let myKey = Cache.Key("my_key")
}
```
Instantiate a live implementation of the cache type.
```swift
let cache = Cache.live()
```
### Insert
```swift
cache.set("string value", at: .myKey)
```
You can provide an optional lifetime in seconds for the entry.
```swift
cache.set("string value", at: .myKey, lifetime: 60)
```
### Retrieve
```swift
let value = cache.retrieve(at: .myKey)
```
### Remove
```swift
cache.remove(at: .myKey)
```
### Usage in tests
This library provides some helpers for easy usage on tests such as:
#### Noop
An implementation of `Cache` that does nothing when called.
```swift
let cache = Cache.noop
```
#### Failing
An implementation of `Cache` that fails with an `XCTFail` call.
```swift
var setEntryCalled = false
let cache = Cache.failing
.override(
setEntry: { entry, key in
setEntryCalled = true
}
)
cache.set("string value", at: .myKey)
XCTAssertTrue(setEntryCalled)
```
At the code snipped above all calls to a method that wasn't overriden will terminate with a `XCTFail`.