subscript(_:)

Provides type-safe access to the context’s values. This API should ONLY be used inside of accessor implementations.

ServiceContext.swift:193
subscript<Key>(key: Key.Type) -> Key.Value? where Key : ServiceContextKey { get set }

End users should use “accessors” the key’s author MUST define rather than using this subscript, following this pattern:

internal enum TestID: ServiceContext.Key {
    typealias Value = TestID
}

extension ServiceContext {
    public internal(set) var testID: TestID? {
        get {
            self[TestIDKey.self]
        }
        set {
            self[TestIDKey.self] = newValue
        }
    }
}

This is in order to enforce a consistent style across projects and also allow for fine grained control over who may set and who may get such property. Just access control to the Key type itself lacks such fidelity.

Note that specific context and context types MAY (and usually do), offer also a way to set context values, however in the most general case it is not required, as some frameworks may only be able to offer reading.