Caching in Swift: Redis, Memcached, and Built-in Solutions from A to Z

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Caching in Swift: Redis, Memcached, and Built-in Solutions: from A to Z



Caching is one of the key performance optimization strategies in iOS and macOS applications. In this article, we will thoroughly examine how to organize caching in Swift: from the built-in NSCache to working with external systems like Redis and Memcached. You will learn when to choose which tool and get ready-made code examples for each approach.



Why is caching needed in Swift applications?



Any application that works with network requests, databases, or heavy computations can benefit from caching. The main advantages:



  • Speed: data from the cache is returned in milliseconds, without network or disk delays.
  • Traffic savings: fewer requests to the server means lower costs for the user and the server.
  • Offline access: with proper implementation, part of the functionality works without the internet.
  • Reduced server load: especially relevant for server-side Swift solutions (Vapor, Kitura).


Built-in Solutions: NSCache and URLCache



NSCache — Lightweight In-Memory Caching



NSCache is a Foundation built-in class for temporary storage of key-value pairs. It automatically removes objects when memory is low, making it ideal for caching images, JSON responses, and other non-critical data.



import Foundation

class ImageCacheManager { static let shared = ImageCacheManager() private let cache = NSCache<NSString, NSData>() func setImageData(_ data: Data, forKey key: String) { cache.setObject(data as NSData, forKey: key as NSString) } func getImageData(forKey key: String) -> Data? { return cache.object(forKey: key as NSString) as Data? } func removeAll() { cache.removeAllObjects() }}

// Usagelet cache = ImageCacheManager.sharedcache.setImageData(imageData, forKey: "avatar_123")if let cachedData = cache.getImageData(forKey: "avatar_123") { print("Data from cache: \\(cachedData.count) bytes")}


Features:

  • Automatic memory management — no need to manually delete objects.
  • Thread-safe — can be used from different threads.
  • Does not guarantee data persistence — the cache can be cleared by the system.


URLCache — HTTP Request Caching



URLCache provides caching at the network request level. It works with URLSession and automatically saves server responses.



import Foundation

// Cache configurationlet memoryCapacity = 50 * 1024 * 1024 // 50 MBlet diskCapacity = 100 * 1024 * 1024 // 100 MBlet urlCache = URLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: "myCache")

URLCache.shared = urlCache

// Session configurationlet config = URLSessionConfiguration.defaultconfig.requestCachePolicy = .returnCacheDataElseLoadconfig.urlCache = urlCache

let session = URLSession(configuration: config)

// Executing the requestlet url = URL(string: "https://api.example.com/data")!let task = session.dataTask(with: url) { data, response, error in if let data = data { print("Received \\(data.count) bytes") // Data is automatically cached }}task.resume()


For fine-tuning caching, use HTTP headers and Cache-Control policies on the server side.



Redis in Swift: Server-Side Caching



Redis is a high-performance in-memory key-value store. For Swift developers working with server-side frameworks (Vapor, Perfect), Redis is the standard choice for caching

Blogs

Book Recommendations