MemoryCache

public class MemoryCache<Key, Element> where Key : Hashable

A high-performance, in-memory key-value cache with configurable thread safety and memory management.

This cache provides automatic expiration, priority-based eviction, and memory usage tracking. It’s designed for scenarios where you need fine-grained control over cache behavior and memory usage.

Initialization

Configuration

  • Configuration options for the memory cache behavior and limits.

    See more

    Declaration

    Swift

    struct Configuration

Public API

  • Returns true if the cache is empty.

    Declaration

    Swift

    var isEmpty: Bool { get }
  • Returns true if the cache is at capacity.

    Declaration

    Swift

    var isFull: Bool { get }
  • The current number of elements in the cache.

    Declaration

    Swift

    var count: Int { get }
  • The maximum capacity of the cache.

    Declaration

    Swift

    var capacity: Int { get }
  • Inserts or updates an element for the given key with optional priority and expiration.

    This method handles both regular elements and null elements, applying appropriate TTL settings and memory cost tracking. When the cache exceeds its memory limit, it automatically evicts entries according to priority-based LRU.

    Note

    Thread safety depends on the enableThreadSynchronization configuration option

    Declaration

    Swift

    @discardableResult
    func set(
        element: Element?,
        for key: Key,
        priority: Double = .zero,
        expiredIn duration: TimeInterval? = nil
    ) -> [Element]

    Parameters

    element

    The element to store (can be nil to cache a null element)

    key

    The key to associate with the element

    priority

    Eviction priority where larger values are retained longer (default: 0)

    duration

    TTL in seconds for this entry. If nil, uses configuration defaults

    Return Value

    Array of evicted elements due to capacity or memory limits

  • Result of a cache fetch attempt for a key.

    See more

    Declaration

    Swift

    enum FetchResult
  • Retrieves the cached state for the given key.

    This method validates the key using the configured validator and returns a FetchResult that distinguishes invalid keys, misses, null-element hits, and non-null element hits. Access updates the LRU order of the entry when present.

    Note

    Thread safety depends on the enableThreadSynchronization configuration option

    Declaration

    Swift

    func getElement(for key: Key) -> FetchResult

    Parameters

    key

    The key to look up

    Return Value

    A FetchResult describing the cache state for key

  • Removes the element for the given key, if present.

    This method removes the entry from the cache and updates the memory cost tracking. The removed element is returned if it existed in the cache.

    Note

    Thread safety depends on the enableThreadSynchronization configuration option

    Declaration

    Swift

    @discardableResult
    func removeElement(for key: Key) -> Element?

    Parameters

    key

    The key to remove

    Return Value

    The removed element, or nil if not found

  • Removes and returns the least recently used element from the cache.

    This method removes the least recently used entry from the cache and returns its element. The removal follows the cache’s eviction policy (priority-based LRU).

    Note

    Thread safety depends on the enableThreadSynchronization configuration option

    Declaration

    Swift

    @discardableResult
    func removeElement() -> Element?

    Return Value

    The removed element, or nil if the cache is empty

  • Removes all expired elements from the cache.

    This method iterates through the cache and removes all entries that have expired based on their TTL (Time-to-Live) settings. This is useful for periodic cleanup to free up memory and maintain cache efficiency.

    Note

    Thread safety depends on the enableThreadSynchronization configuration option

    Declaration

    Swift

    func removeExpiredElements()
  • Removes cache entries to reduce the cache size to a specified percentage of its current size.

    This method first removes all expired elements, then continues removing the least recently used entries until the cache size reaches the specified percentage of its original size.

    Note

    Thread safety depends on the enableThreadSynchronization configuration option

    Declaration

    Swift

    func removeElements(toPercent: Double)

    Parameters

    toPercent

    The target percentage (0.0 to 1.0) of current cache size to retain

  • Resets all recorded cache statistics to zero.

    This clears counters such as hit/miss counts and total accesses. Useful for measuring statistics over distinct time windows.

    Declaration

    Swift

    func resetStatistics()