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.

Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover

Check out our book!

Integrating SwiftUI into UIKit Apps

Integrating SwiftUI intoUIKit Apps

UPDATED FOR iOS 17!

A detailed guide on gradually adopting SwiftUI in UIKit projects.

  • Discover various ways to add SwiftUI views to existing UIKit projects
  • Use Xcode previews when designing and building UI
  • Update your UIKit apps with new features such as Swift Charts and Lock Screen widgets
  • Migrate larger parts of your apps to SwiftUI while reusing views and controllers built in UIKit