重载字典下标两次并转发调用

Overload dictionary subscript two times and forward call

我正在尝试扩展 Dictionary 并允许提取转换为特定类型并具有给定默认值的值。为此,我为 subscript 函数添加了两个重载,一个具有默认值,一个没有:

extension Dictionary {

    subscript<T>(_ key: Key, as type: T.Type, defaultValue: T?) -> T? {
        // the actual function is more complex than this :)
        return nil
    }

    subscript<T>(_ key: Key, as type: T.Type) -> T? {
        // the following line errors out:
        // Extraneous argument label 'defaultValue:' in subscript
        return self[key, as: type, defaultValue: nil]
    }
}

然而,当从两个参数的下标调用三个参数的下标时,出现以下错误:

Extraneous argument label 'defaultValue:' in subscript

这是 Swift 限制吗?还是我遗漏了什么?

我正在使用 Xcode 10.2 beta 2。

P.S。我知道还有其他替代方法,比如专用函数或 nil 合并,试图了解在这种特定情况下出了什么问题。

在参数标签方面,下标与函数有不同的规则。对于函数,参数标签默认为参数名称——例如,如果您定义:

func foo(x: Int) {}

你可以称它为 foo(x: 0)

但是对于下标,参数默认没有参数标签。因此,如果您定义:

subscript(x: Int) -> X { ... }

你会称它为 foo[0] 而不是 foo[x: 0]

因此在您的示例中带有下标:

subscript<T>(_ key: Key, as type: T.Type, defaultValue: T?) -> T? {
    // the actual function is more complex than this :)
    return nil
}

defaultValue:参数没有参数标签,这意味着下标必须被称为self[key, as: type, nil]。为了添加参数标签,需要指定两次:

subscript<T>(key: Key, as type: T.Type, defaultValue defaultValue: T?) -> T? {
    // the actual function is more complex than this :)
    return nil
}