/SwiftyCache

A lightweight, elegant, and performant in-memory cache written purely in Swift

Primary LanguageSwiftMIT LicenseMIT

πŸ’Ύ SwiftyCache

Swift Package Manager License: MIT Platform Contact

SwiftyCache is a lightweight, elegant, and performant in-memory cache written purely in Swift.
It supports Least-Recently-Used (LRU) eviction logic using Swift Collections’ OrderedDictionary, with optional cost-based cleanup and memory warning handling for Apple platforms.

Simple. Fast. Swifty.


πŸš€ Features

  • βœ… LRU (Least-Recently-Used) eviction strategy
  • βœ… Cost-based cleanup (totalCostLimit)
  • βœ… Count-based cleanup (countLimit)
  • βœ… MemoryWarning cleanup
  • βœ… Thread-safe design ready
  • βœ… No Objective-C / Foundation subclassing
  • βœ… 100% Swift + SPM support
  • βœ… Clean and minimal API

πŸ“¦ Installation

Swift Package Manager

dependencies: [
    .package(url: "https://github.com/codingiran/SwiftyCache.git", from: "1.0.0")
]

Then import where needed:

import SwiftyCache

🧩 Usage

Create a cache

let cache = SwiftyCache<String, Data>(
    totalCostLimit: 10_000,  // Optional
    countLimit: 100          // Optional
)

Store & retrieve values

cache.setValue(imageData, forKey: "avatar", cost: imageData.count)

let cachedData = cache.value(forKey: "avatar")

Eviction

  • Least Recently Used items are automatically evicted when:

Remove items

cache.removeValue(forKey: "avatar")
cache.removeAllValues()

πŸ§ͺ LRU Example

let cache = SwiftyCache<String, Int>(countLimit: 3)

cache.setValue(1, forKey: "A")
cache.setValue(2, forKey: "B")
cache.setValue(3, forKey: "C")

_ = cache.value(forKey: "A") // A is now most recently used

cache.setValue(4, forKey: "D") // B is evicted (least recently used)

print(cache.allKeys) // ["C", "A", "D"]

🧱 Implementation Highlights

  • Using Swift actor for thread safety
  • Implements NSCache-like API for easy integration
  • Built atop OrderedDictionary to avoid managing doubly-linked list manually
  • Reorders keys internally on access to preserve LRU order
  • Minimal dependencies, cleanly integrated with DispatchSourceMemoryPressure for memory warnings

πŸ“ Project Structure

SwiftyCache/
β”œβ”€β”€ Sources/
β”‚   └── SwiftyCache.swift
β”œβ”€β”€ Package.swift
└── README.md ← You are here

πŸ“„ License

This project is licensed under the MIT License.
See LICENSE for more information.


🀝 Contributing

Pull requests are welcome!
If you'd like to add a feature, fix a bug, or improve documentation:

  • Fork the repo
  • Create your feature branch: git checkout -b feature/your-feature
  • Commit your changes: git commit -m "Add some feature"
  • Push to the branch: git push origin feature/your-feature
  • Open a Pull Request

πŸ“¬ Contact

Feel free to reach out:

πŸ“§ Email: codingiran@gmail.com
πŸ“¦ GitHub: github.com/codingiran/SwiftyCache


Made with ❀️ by @codingiran