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.