我正在尝试扩展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]
}
}
但是,当从两个参数中调用三个参数的下标时,出现以下错误:
下标中的外部参数标签'defaultValue:'
这是Swift的限制吗?还是我错过了什么?
我正在使用Xcode 10.2 beta 2。
P.S。我知道还有其他替代方法,例如专用函数或零合并,试图了解在这种特殊情况下出了什么问题。
答案 0 :(得分:3)
对于参数标签,下标与函数的规则不同。对于函数,参数标签默认为参数名称-例如,如果您定义:
_
您将其称为let _i_swear_to_hb_curry_i_know_what_i_m_doing =
Format.printf "side-effect!@."; List.iter (fun () -> ());;
。
但是,对于下标,默认情况下参数没有参数标签。因此,如果您定义:
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: