NEW BOOK! Swift Gems: 100+ tips to take your Swift code to the next level. Learn more ...NEW BOOK! Swift Gems:100+ advanced Swift tips. Learn more...

Mutable static properties in generic types and protocol extensions

We currently can't add static mutable properties to generic types in Swift. If we try to do it, the compiler gives us an error Static stored properties not supported in generic types.

To work around this limitation we can use the ObjectIdentifier function that provides a stable Hashable value for each generic concrete type.

fileprivate var _gValues: [ObjectIdentifier: Any] = [:]

struct MyValue<T> {
    static var a: Int {
        get {
            _gValues[ObjectIdentifier(Self.self)] as? Int ?? 42
        }

        set {
            _gValues[ObjectIdentifier(Self.self)] = newValue
        }
    }
}

We can also apply this solution to create mutable static properties in extensions. This includes extensions to protocol types, where the value storage is local to the final concrete type conforming to the protocol.

protocol LocalStore {
    associatedtype StoredValue
    static var defaultValue: StoredValue { get }
    static var cache: StoredValue { get set }
}

extension LocalStore {
    static var cache: StoredValue {
        get {
            _gValues[ObjectIdentifier(Self.self)] as? StoredValue
                ?? defaultValue
        }
        set {
            _gValues[ObjectIdentifier(Self.self)] = newValue
        }
    }
}

Types that conform to the protocol just need to define a read-only default value. This can be a computed property, so it can be defined in the extension that provides conformance.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Check out our new book!

Swift Gems

100+ tips to take your Swift code to the next level

Swift Gems

100+ tips to take your Swift code to the next level

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms
  • Practical Swift insights from years of development, applicable from iOS to server-side Swift