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

Introduction: Why Caching in Swift Applications?

\n

Caching is one of the key techniques for optimizing the performance of mobile and server applications. In the world of Swift (iOS/macOS), proper caching reduces data loading time, decreases network and database load, and improves the user experience. In this article, we will cover three main approaches to caching in Swift: the built-in NSCache solution, the popular server systems Redis and Memcached, as well as their integration into iOS/macOS projects.

\n\n

1. Built-in Caching: NSCache and URLCache

\n

For most iOS applications, external servers are not required — Apple's built-in mechanisms are sufficient.

\n\n

1.1 NSCache — Simple and Efficient In-Memory Cache

\n

NSCache is a thread-safe dictionary that automatically removes objects when memory is low. It is ideal for caching images, JSON responses, or any computationally expensive objects.

\n
import Foundation\n\nclass ImageCache {\n    private let cache = NSCache<NSString, NSData>()\n\n    func setImageData(_ data: Data, forKey key: String) {\n        cache.setObject(data as NSData, forKey: key as NSString)\n    }\n\n    func getImageData(forKey key: String) -> Data? {\n        return cache.object(forKey: key as NSString) as Data?\n    }\n}
\n

Tip: Configure the countLimit and totalCostLimit limits for optimal performance.

\n\n

1.2 URLCache — Caching Network Requests

\n

URLCache automatically caches HTTP responses on disk and in memory. Configuration is done via URLSessionConfiguration:

\n
let config = URLSessionConfiguration.default\nconfig.urlCache = URLCache(memoryCapacity: 50 * 1024 * 1024,  // 50 MB\n                           diskCapacity: 100 * 1024 * 1024, // 100 MB\n                           diskPath: "myCache")\nlet session = URLSession(configuration: config)
\n

This is especially useful for static content (images, API responses with a long time-to-live).

\n\n

2. Redis in Swift Projects

\n

Redis is an in-memory data store supporting structures (strings, lists, hashes). In Swift Server-side projects (Vapor, Perfect), Redis is used for sessions, queues, and fast caching.

\n\n

2.1 Connecting Redis via Vapor

\n

Vapor provides the vapor/redis package. Installation:

\n
// Package.swift\ndependencies: [\n    .package(url: "https://github.com/vapor/redis.git", from: "4.0.0")\n]
\n

Example of caching user data:

\n
import Vapor\nimport Redis\n\nfunc cacheUser(_ user: User, on request: Request) async throws {\n    let key = "user:\\(user.id)"\n    let data = try JSONEncoder().encode(user)\n    try await request.redis.set(key, to: data)\n    // Setting TTL (time to live) 1 hour\n    try await request.redis.expire(key, after: .hours(1))\n}\n\nfunc getUser(from request: Request, id: Int) async throws -> User? {\n    let key = "user:\\(id)"\n    guard let data = try await request.redis.get(key, as: Data.self) else {\n        return nil\n    }\n    return try JSONDecoder().decode(User.self, from: data)\n}
\n\n

2.2 Advantages of Redis for Swift

\n
    \n
  • Speed: data is stored in RAM — latency under a millisecond.
  • \n
  • TTL: automatic key expiration.
  • \n
  • Pub/Sub: asynchronous communication between services.
  • \n
\n\n

3. Memcached: Lightweight Distributed Caching

\n

Memcached is an older but still popular caching system. Unlike Redis, it does not support complex data structures or persistence, but it is extremely simple and efficient for key-value caching.

\n\n

3.1 Integrating Memcached in Swift

Blogs

Book Recommendations