Weekly Swift articles, podcasts and tips by John Sundell.

Adding the current locale to cache keys

Published on 23 Aug 2017

When caching localized content in an app, it's a good idea to add the current locale to all keys, to prevent bugs when switching languages.

func cache(_ content: Content, forKey key: String) throws {
    let data = try wrap(content) as Data
    let key = localize(key: key)
    try storage.store(data, forKey: key)
}

func loadCachedContent(forKey key: String) -> Content? {
    let key = localize(key: key)
    let data = storage.loadData(forKey: key)
    return data.flatMap { try? unbox(data: $0) }
}

private func localize(key: String) -> String {
    return key + "-" + Bundle.main.preferredLocalizations[0]
}

Support Swift by Sundell by checking out this sponsor:

Magic Lasso Adblock
Magic Lasso Adblock

Magic Lasso Adblock: Block ads, trackers and pop-ups on your iPhone, iPad and Mac. Magic Lasso Adblock provides a 2.0x speed increase on common websites, improves your privacy by removing ad trackers and works with Safari across all devices. It’s as if Apple themselves had designed an ad blocker. Download for free today.