Hex Color Parsing in Swift: Cache UIColor for Speed
Avoid repeated hex parsing in UIKit by caching computed colors for faster view re-renders.
Hex Color Parsing in Swift: Cache UIColor for Speed
If your UI rebuilds often, repeatedly converting the same hex strings to UIColor wastes CPU cycles.
Solution
Use a static dictionary cache keyed by normalized hex values, and return the cached color before parsing again.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import UIKit
extension UIColor {
private static var hexColorCache: [String: CGColor] = [:]
private static let cacheLock = NSLock()
convenience init?(hex: String) {
let cleanedHex = hex
.trimmingCharacters(in: .whitespacesAndNewlines)
.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
.uppercased()
Self.cacheLock.lock()
if let cachedColor = Self.hexColorCache[cleanedHex] {
Self.cacheLock.unlock()
self.init(cgColor: cachedColor)
return
}
Self.cacheLock.unlock()
guard cleanedHex.count == 6,
let rgbValue = UInt64(cleanedHex, radix: 16)
else { return nil }
let red = CGFloat((rgbValue >> 16) & 0xFF) / 255
let green = CGFloat((rgbValue >> 8) & 0xFF) / 255
let blue = CGFloat(rgbValue & 0xFF) / 255
self.init(red: red, green: green, blue: blue, alpha: 1)
Self.cacheLock.lock()
Self.hexColorCache[cleanedHex] = self.cgColor
Self.cacheLock.unlock()
}
}
This optimization is most useful in reusable cells, dynamic theming, and frequently recomputed Swift/UIKit view trees.
When to Use
- You construct colors from the same hex strings repeatedly.
- You parse colors inside render/update paths.
- You need a low-effort optimization with minimal API changes.
☕ Support My Work
If you found this post helpful and want to support more content like this, you can buy me a coffee!
Your support helps me continue creating useful articles and tips for fellow developers. Thank you! 🙏
This post is licensed under CC BY 4.0 by the author.