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

Level up your Swift skills!$35

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

Swift Gemsby Natalia Panferova

  • 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

Level up your Swift skills!

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

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

Swift Gems

by Natalia Panferova

$35