The Swift Cooperative

Authors publishing advanced articles on Swift and SwiftUI application development.

Follow publication

Member-only story

Swift High Performance: Dictionary Keys

Michael Long
The Swift Cooperative
11 min readAug 27, 2023

--

Photo by Chunli Ju on Unsplash

This article is an in-depth exploration of how to create dictionary keys that are fast and performant under all circumstances, and why String-based keys often fail in that regard.

It includes actual examples and performance data taken from Factory, my open-source dependency injection library.

Ready? Let’s get into it.

Caching

A common practice in any application is to create some expensive item, cache that item in a key-based dictionary, and then check later on to see if that item exists, returning the cached value if it does.

An extremely rudimentary implementation of that might be:

class ItemRepository {
private var cache = [String:Item]()
func item(forKey key: String) -> Item? {
if let item = cache[key] {
return item
}
let item = Item(key: key)
cache[key] = item
return item
}
}

We’ve all seen or done some variation of this.

But the fundamental problem we have here is that using a Swift String as our dictionary key isn’t an optimal choice. Far…

--

--

The Swift Cooperative
The Swift Cooperative

Published in The Swift Cooperative

Authors publishing advanced articles on Swift and SwiftUI application development.

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

Responses (9)

Write a response