Swift error when trying to access Dictionary: `Could not find member 'subscript'`

后端 未结 4 906
半阙折子戏
半阙折子戏 2021-02-04 08:08

This won\'t compile: \"enter I\'ve tried a couple different things; different ways of declaring th

4条回答
  •  被撕碎了的回忆
    2021-02-04 08:25

    response is declared as such:

    var response = Dictionary()
    

    So the compiler thinks response["current_rates"] will return an Any. Which may or may not be something that is subscript indexable.

    You should be able to define you type with nested Dictionaries, 3 levels and eventually you get to a float. You also need to drill in with optional chaining since the dictionary may or may not have a value for that key, so it's subscript accessor returns an optional.

    var response = Dictionary>>()
    // ... populate dictionaries
    println(response["current_rates"]?["a"]?["b"]) // The float
    

提交回复
热议问题