两次重载字典下标并向前调用

Cri*_*tik 3 overloading swift

我正在尝试扩展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]
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当从两个参数之一调用三个参数的下标时,出现以下错误:

下标中的无关参数标签“ defaultValue:”

在此处输入图片说明

这是Swift的限制吗?还是我错过了什么?

我正在使用Xcode 10.2 beta 2。

PS我知道,还有其他替代方法,例如专用功能或零合并,试图了解在这种特殊情况下出了什么问题。

Ham*_*ish 5

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

func foo(x: Int) {}
Run Code Online (Sandbox Code Playgroud)

您将其称为foo(x: 0)

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

subscript(x: Int) -> X { ... }
Run Code Online (Sandbox Code Playgroud)

您会称其为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
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

  • @trojanfoe此处记录:https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#grammar_subscript-declaration –“ *默认情况下,用于下标的参数没有参数标签,与函数不同,方法和初始值设定项。但是,您可以使用函数,方法和初始值设定项使用的相同语法来提供显式参数标签。*“ (2认同)