问题描述
我正在尝试扩展 Dictionary
并允许提取转换为特定类型和给定默认值的值.为此,我为 subscript
函数添加了两个重载,一个有默认值,一个没有:
I'm trying to extend Dictionary
and allow extracting values casted to a certain types and with a given default value. For this I added two overloads for the subscript
function, one with a default value, one without:
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]
}
}
但是,当从二元下标调用三元下标时,出现以下错误:
However when calling the three-argument subscript from the two-argument one I get the following error:
下标中的无关参数标签defaultValue:"
这是 Swift 的限制吗?还是我遗漏了什么?
Is this a Swift limitation? Or am I missing something?
我使用的是 Xcode 10.2 beta 2.
I'm using Xcode 10.2 beta 2.
附言我知道还有其他替代方法,例如专用函数或 nil 合并,试图了解在这种特定情况下出了什么问题.
P.S. I know there are other alternatives to this, like dedicated functions or nil coalescing, trying to understand what went wrong in this particular situation.
推荐答案
当涉及到参数标签时,下标与函数有不同的规则.对于函数,参数标签默认为参数名称——例如,如果您定义:
Subscripts have different rules than functions when it comes to argument labels. With functions, argument labels default to the parameter name – for example if you define:
func foo(x: Int) {}
您可以将其称为 foo(x: 0)
.
然而对于下标,参数默认没有参数标签.因此,如果您定义:
However for subscripts, parameters don't have argument labels by default. Therefore if you define:
subscript(x: Int) -> X { ... }
你会称它为 foo[0]
而不是 foo[x: 0]
.
you would call it as foo[0]
rather than foo[x: 0]
.
因此在您的示例中带有下标:
Therefore in your example with the subscript:
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]
.为了添加参数标签,您需要指定两次:
The defaultValue:
parameter has no argument label, meaning that the subscript would have to be called as self[key, as: type, nil]
. In order to add the argument label, you need to specify it twice:
subscript<T>(key: Key, as type: T.Type, defaultValue defaultValue: T?) -> T? {
// the actual function is more complex than this :)
return nil
}
这篇关于重载字典下标两次并转发调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!