Overload dictionary subscript two times and forward call

僤鯓⒐⒋嵵緔 提交于 2020-02-03 15:12:28

问题


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:

Extraneous argument label 'defaultValue:' in subscript

Is this a Swift limitation? Or am I missing something?

I'm using Xcode 10.2 beta 2.

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.


回答1:


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) {}

you would call it as foo(x: 0).

However for subscripts, parameters don't have argument labels by default. Therefore if you define:

subscript(x: Int) -> X { ... }

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
}

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
}


来源:https://stackoverflow.com/questions/54710144/overload-dictionary-subscript-two-times-and-forward-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!