A modern, lightweight image caching library for iOS and macOS. Built with 100% Apple native APIs—zero dependencies.
- ✅ Zero Dependencies - Pure Swift, no third-party frameworks
- ✅ Lightweight - Optimized for performance and app size (~150KB)
- ✅ Cross-Platform - Full support for iOS, macOS, tvOS, and watchOS
- ✅ TTL Support - Automatic cache expiration with customizable time-to-live
- ✅ Three-Tier Caching - Memory → Disk → Network with Chain of Responsibility pattern
- ✅ Progressive Loading - Show thumbnails while loading full images
- ✅ Automatic Downscaling - Reduce memory usage on both iOS and macOS
- ✅ Lifecycle Aware - Automatically manages memory in background/foreground
- ✅ Thread Safe - Built with Swift Concurrency (actors) and async/await
- ✅ Modern Swift - Actor-based architecture, no GCD mixing
- ✅ Extensible - Strategy pattern allows custom cache implementations
- ✅ Cancellable Requests - Cancel downloads when cells are reused
- ✅ LRU Eviction - Automatic cleanup of old cached images
- ✅ Analytics - Built-in performance metrics and cache statistics
- ✅ Swift 6 Ready - Full Sendable conformance and strict concurrency
dependencies: [
.package(url: "https://github.com/SudhirGadhvi/SwiftCache-SDK", from: "2.0.0")
]pod 'SwiftCacheSDK', '~> 2.0'import SwiftCache
// Simple usage
imageView.sc.setImage(with: url)
// With placeholder
imageView.sc.setImage(with: url, placeholder: UIImage(systemName: "photo"))
// With completion
imageView.sc.setImage(with: url) { result in
switch result {
case .success(let image):
print("Image loaded: \(image.size)")
case .failure(let error):
print("Failed: \(error)")
}
}
// Async/await (iOS 15+)
Task {
do {
let image = try await imageView.sc.setImage(with: url)
print("Image loaded: \(image.size)")
} catch {
print("Failed: \(error)")
}
}Modern SwiftUI (iOS 15+):
import SwiftUI
import SwiftCache
struct ContentView: View {
var body: some View {
NavigationStack {
CachedImage(url: imageURL) {
ProgressView()
}
.frame(width: 300, height: 300)
.clipShape(RoundedRectangle(cornerRadius: 12))
}
}
}Key modern features:
- Uses
.task(id:)for automatic cancellation and restart on URL changes - No manual
MainActor.runcalls - proper SwiftUI integration - Follows modern SwiftUI patterns (iOS 15+)
// Configure global settings
Task {
await SwiftCache.shared.configure { config in
config.memoryCacheLimit = 100 * 1024 * 1024 // 100MB
config.diskCacheLimit = 1024 * 1024 * 1024 // 1GB
config.defaultTTL = 86400 // 24 hours
config.enableAnalytics = true
// Enable automatic downscaling (works on iOS and macOS)
config.maxImageDimension = 2048 // Max 2048px on longest side
}
}SwiftCache uses the Strategy Pattern to allow custom implementations for each cache layer:
// Create a custom loader (must be an actor)
actor MyCustomMemoryLoader: CacheLoader {
func load(key: String, url: URL, ttl: TimeInterval) async -> SCImage? {
// Your custom memory cache implementation
return nil
}
func store(image: SCImage, key: String, ttl: TimeInterval) async {
// Your custom storage logic
}
func clear() async {
// Your custom clear logic
}
}
// Set custom loaders (async call)
Task {
await SwiftCache.shared.setCustomLoaders([
MyCustomMemoryLoader(),
MyCustomDiskLoader(),
MyCustomNetworkLoader()
])
}This makes SwiftCache incredibly flexible - use your own cache backends, network layers, or storage mechanisms!
| Library | Binary Size | Memory Cache | Disk Cache | TTL Support | Progressive Loading | Dependencies |
|---|---|---|---|---|---|---|
| SwiftCache | 150KB | ✅ | ✅ | ✅ | ✅ | 0 |
| Kingfisher | 500KB | ✅ | ✅ | Limited | ✅ | 0 |
| SDWebImage | 800KB | ✅ | ✅ | ❌ | ✅ | 0 |
Initial Release
- Three-tier caching system (Memory → Disk → Network)
- TTL (time-to-live) support with automatic expiration
- UIImageView extension for easy integration
- SwiftUI
CachedImageview - Callback-based APIs
- Progressive loading (thumbnail → full image)
- Cache analytics and performance metrics
- Cancellable requests with token-based cancellation
- Lifecycle-aware memory management
- LRU disk cache cleanup
- Cross-platform support (iOS, macOS, tvOS, watchOS)
- Zero external dependencies
- Image downscaling (iOS only)
Major Architecture Rewrite - Swift Concurrency & Design Patterns
- Actor-based architecture - Pure Swift Concurrency
- Chain of Responsibility pattern - Clean cache fallback
- Strategy pattern - Pluggable custom loaders
- Async/await native APIs - Modern Swift
- macOS downscaling support - Feature parity with iOS
- Custom loader API - Extensibility for Redis, S3, etc.
- Granular metrics - Per-layer performance tracking
- Swift 6 ready - Full Sendable conformance
- Removed all GCD - No DispatchQueue mixing
- Fixed MainActor blocking - Proper isolation
- Thread-safe by design - Compiler-enforced safety
- Backward compatible - Callback APIs maintained
- Comprehensive tests - 11 tests covering all features
- Architecture guide - Deep dive documentation
Reactive & Format Support
- Combine Support - Publishers for reactive programming
- GIF Animation Support - Animated image caching
- WebP Format Support - Modern image format
- Custom Image Processors - Transform images before caching
- Network Reachability - Pause downloads when offline
- Batch Operations - Bulk prefetch/clear operations
Intelligence & UX
- Prefetching API - Intelligent prefetch with priority
- Image Placeholders - Blurhash/ThumbHash support
- Cache Warming - Preload frequently used images
- Memory Pressure Monitoring - Adaptive cache limits
- Smart Eviction - Usage-based cache management
- Request Coalescing - Deduplicate simultaneous requests
Advanced Features & Cloud
- Advanced Transformations - Resize, crop, filters, effects
- Video Thumbnail Caching - Extract and cache video frames
- CloudKit Sync - Sync cache across devices
- Custom Disk Paths - Multi-level disk cache
- SwiftData Integration - Modern persistence layer
- Background Downloads - URLSession background transfer
- Streaming Support - Progressive JPEG/PNG decoding
Next-Gen & ML
- AVIF Format Support - Next-gen image format
- HEIF/HEIC Optimization - Native Apple format improvements
- Smart Cache Eviction - ML-based prediction
- CDN Integration - Cloudflare, CloudFront adapters
- Image Quality Adaptation - Automatic quality based on network
- Distributed Caching - Multi-device cache sharing
- Server-Side Swift - Vapor/Hummingbird integration
Want a feature? Open an issue or submit a PR!
Contributions are welcome! Please read CONTRIBUTING.md first.
SwiftCache is released under the MIT License. See LICENSE for details.
Sudhir Gadhvi
- LinkedIn: Sudhir Gadhvi
Inspired by real-world challenges in building modern iOS apps.
⭐️ If you like SwiftCache, give it a star!