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.
- ✅ LRU (Least-Recently-Used) eviction strategy
- ✅ Cost-based cleanup (
totalCostLimit) - ✅ Count-based cleanup (
countLimit) - ✅ Memory-pressure cleanup via
DispatchSourceMemoryPressure - ✅ Actor-isolated thread-safe design
- ✅ No Objective-C / Foundation subclassing
- ✅ 100% Swift + SPM support
- ✅ Clean and minimal API
dependencies:[.package(url:"https://github.com/codingiran/SwiftyCache.git", from:"1.0.0")]Then import where needed:
import SwiftyCacheletcache=SwiftyCache<String,Data>(
totalCostLimit:10_000, // Optional
countLimit:100 // Optional
)func cacheAvatar(_ imageData:Data)async{await cache.setValue(imageData, forKey:"avatar", cost: imageData.count)letcachedData=await cache.value(forKey:"avatar")}- Least Recently Used items are automatically evicted when:
countLimitis exceededtotalCostLimitis exceeded- Memory pressure (DispatchSourceMemoryPressure) is received
await cache.setCountLimit(50)await cache.setTotalCostLimit(5_000)await cache.setClearOnMemoryPressure(false)await cache.setName("avatars")await cache.removeValue(forKey:"avatar")await cache.removeAllValues()func lruExample()async{letcache=SwiftyCache<String,Int>(countLimit:3)await cache.setValue(1, forKey:"A")await cache.setValue(2, forKey:"B")await cache.setValue(3, forKey:"C")
_ =await cache.value(forKey:"A") // A is now most recently used
await cache.setValue(4, forKey:"D") // B is evicted (least recently used)
print(await cache.allKeys) // ["C", "A", "D"]
}- Using Swift actor for thread safety
- Implements
NSCache-like API for easy integration - Built atop
OrderedDictionaryto avoid managing doubly-linked list manually - Reorders keys internally on access to preserve LRU order
- Minimal dependencies, cleanly integrated with
DispatchSourceMemoryPressurefor memory warnings
SwiftyCache/├── Sources/│└── SwiftyCache/│├── SwiftyCache.swift
│└── Resources/│└── PrivacyInfo.xcprivacy
├── Tests/│└── SwiftyCacheTests/│└── SwiftyCacheTests.swift
├──Package.swift
├── Package@swift-5.10.swift
└──README.md ← You are hereThis project is licensed under the MIT License.
See LICENSE for more information.
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
Feel free to reach out:
📧 Email: codingiran@gmail.com
📦 GitHub: github.com/codingiran/SwiftyCache
Made with ❤️ by @codingiran