Caching in Swift: Redis, Memcached, and Built-in Solutions for iOS/macOS

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

Introduction: Why Caching is Needed in Swift Applications?

Modern iOS and macOS applications work with large volumes of data: images, JSON responses from APIs, computation results. Without caching, every data access leads to repeated loading or recalculation, which negatively impacts performance, traffic consumption, and response time. Caching in Swift is a strategy for temporarily storing frequently used data in fast storage (RAM or local disk) to speed up access.

In this article, we will look at three main approaches to caching in the Swift ecosystem:

  • Built-in solutions: NSCache and URLCache — lightweight and efficient tools for most tasks.
  • Redis — a powerful server-side cache for distributed systems.
  • Memcached — a high-performance in-memory caching system.

You will learn how to integrate each of these tools into a Swift project, see code examples, and understand which option to choose for a specific task.



Built-in Solutions: NSCache and URLCache

Apple provides two powerful built-in caching mechanisms that do not require installing third-party libraries. They are ideal for 90% of tasks in mobile development.



NSCache — In-Memory Caching

NSCache is a thread-safe dictionary with automatic memory management. It automatically removes objects when RAM is low, making it ideal for caching images, data models, and any heavy objects.

import Foundation

// Create a cache for UIImagelet imageCache = NSCache<NSString, UIImage>()

// Function to load an image with cachingfunc loadImage(from url: URL, completion: @escaping (UIImage?) -> Void) { // Check the cache if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) { completion(cachedImage) return } // Load data URLSession.shared.dataTask(with: url) { data, response, error in guard let data = data, let image = UIImage(data: data) else { completion(nil) return } // Save to cache imageCache.setObject(image, forKey: url.absoluteString as NSString) completion(image) }.resume()}

Advantages of NSCache:

  • Automatic clearing on memory warning
  • Thread safety without additional locks
  • Ability to set limits on the number of objects and total cost


URLCache — HTTP Response Caching

URLCache is a system cache for HTTP requests. It saves server responses to disk and memory, automatically managing their lifetime based on HTTP headers (Cache-Control, Expires).

import Foundation

// Configure URLCache (usually in AppDelegate or SceneDelegate)let cacheSize = 50 * 1024 * 1024 // 50 MBlet urlCache = URLCache(memoryCapacity: cacheSize, diskCapacity: cacheSize, diskPath: "myCache")URLCache.shared = urlCache

// Example request with cachinglet request = URLRequest(url: URL(string: "https://api.example.com/data")!)URLSession.shared.dataTask(with: request) { data, response, error in // URLCache will automatically handle caching // based on Cache-Control headers}.resume()

When to use URLCache:

  • For caching REST API responses
  • For static resources (images, configuration files)
  • When you need to comply with the server's caching policy


Redis — Distributed Cache for Server-Side Swift

Redis is a high-performance in-memory data store often used as a cache server. For Swift, there are several clients, the most popular

Blogs

Book Recommendations