0

I am using some new features of Swift 4 programming language. For some reason it is complaining in the below code where I am returning the self[key] value.

extension Dictionary {

    subscript<T>(key :String, type :T) -> T? {
        get {
            return self[key] as? T // this line
        }
    }
}

MyPlayground.playground:1:5: note: found this candidate

subscript<T>(key :String, type :T) -> T? {

Any ideas what I am doing wrong?

UPDATE:

extension Dictionary {

    subscript<T>(key :Key) -> T? {
        return self[key] as? T
    }
}

struct Pokemon {
    var title :String
}

let pokemon = Pokemon(title: "Pikachu")

var dictionary = [String:Any]()
dictionary["foo"] = "hello world"
dictionary["pokemon"] = pokemon

let p = dictionary["pokemon"] // this calls the default subscript not mine
john doe
  • 9,220
  • 23
  • 91
  • 167
  • Not all dictionaries have `String` keys ;) – Hamish May 18 '17 at 19:47
  • Thats true! But am I not creating a different subscript function which has String as a key. – john doe May 18 '17 at 19:57
  • 1
    But the subscript you're trying to implement takes a `String` key – you meant `Key`. – Hamish May 18 '17 at 20:00
  • Compare [Swift Dictionary access value using key within extension](http://stackoverflow.com/q/41133595/2976878). Also you probably meant for the `type` parameter to take a `T.Type`. – Hamish May 18 '17 at 20:19
  • Also even though I have the subscript property added as an extension when I use dictionary it always uses the default implementation. Any way to change that to pick my implementation of subscript – john doe May 18 '17 at 20:21
  • I'm not running Swift 4, so cannot test, but I don't see what other subscript could be called for `dict[someKey, someType]` – are you sure that's how you're calling it? – Hamish May 18 '17 at 20:24
  • I have updated the code. – john doe May 18 '17 at 20:25
  • 1
    If you explicitly annotate `p` as something other than `Any`, your subscript should be called. But really that's quite an unclear addition to the dictionary API, I would keep it with an explicit `type:` parameter. Also I *suspect* that your implementation of the subscript will infinitely recurse. – Hamish May 18 '17 at 20:31
  • Basically they added support for Generic Type Subscripts. – john doe May 18 '17 at 20:32

0 Answers0