对于参数标签,下标与函数有不同的规则。对于函数,参数标签默认为参数名称,例如,如果您定义:
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
}