Search code examples
swiftlabelsubscript

Swift subscript with argument label


Is it possible to create a subscript that can be invoked with explicit argument labels?

struct MyType {
    subscript (label: Bool) -> String? {
        return nil
    }
}

let test = MyType()
let value1 = test[true] // ok
let value2 = test[label: true] // Extraneous argument label 'label:' in subscript

Attempting to use the label results in the error:

Extraneous argument label 'label:' in subscript

The new key path feature looks like it uses subscripts with argument labels, but that may be compiler magic that isn't available to the public:

let value = someThing[keyPath: \.property]

Solution

  • External argument labels in subscript aren't used by default, so unlike for normal functions, if you want to have external argument labels, you need to specify that explicitly.

    struct MyType {
        subscript(label label: Bool) -> String? {
            return nil
        }
    }
    
    let test = MyType()
    let value = test[label: true]