Cache

0.1.0

A type-safe swifty wrapper around NSCache.
binaryscraping/swift-cache

What's New

0.1.0 🚀

2022-05-13T11:53:59Z

swift-cache

A type-safe swifty wrapper around NSCache.

Getting Started

Add swift-cache as a dependency to your project using SPM.

.package(url: "https://github.com/binaryscraping/swift-cache", from: "0.1.0"),

And in your application/target, add "Cache" to your "dependencies".

.target(
  name: "YourTarget",
  dependencies: [
    .product(name: "Cache", package: "swift-cache"),
  ]
)

Usage

Cache is accessed through a CacheKey type, so start by defining your keys.

extension CacheKey where Value == String {
  // A key that stores a string value.
  static let myKey = CacheKey("my_key")
}

Instantiate a live implementation of the cache type.

let cache = Cache.live()

Insert

cache.set("string value", at: .myKey)

You can provide an optional lifetime in seconds for the entry.

cache.set("string value", at: .myKey, lifetime: 60)

Retrieve

let value = cache.retrieve(at: .myKey)

Remove

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.

let cache = Cache.noop

Failing

An implementation of Cache that fails with an XCTFail call.

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.

Description

  • Swift Tools 5.6.0
View More Packages from this Author

Dependencies

Last updated: Fri Oct 18 2024 16:44:21 GMT-0900 (Hawaii-Aleutian Daylight Time)