我正在尝试扩展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我知道,还有其他替代方法,例如专用功能或零合并,试图了解在这种特殊情况下出了什么问题。
对于参数标签,下标与函数的规则不同。对于函数,参数标签默认为参数名称-例如,如果您定义:
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)
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |