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

后端 未结 4 882
半阙折子戏
半阙折子戏 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:27

    Let's take a look at

    response["current_rates"][exchange][currency]
    

    response is declared as Dictionary(), so after the first subscript you try to call another two subscripts on an object of type Any.

    Solution 1. Change the type of response to be a nested dictionary. Note that I added the question marks because anytime you access a dictionary item you get back an optional.

    var response = Dictionary>>()
    
    func valueForCurrency(currency :String, exchange :String) -> Float? {
        return response["current_rates"]?[exchange]?[currency]
    }
    

    Solution 2. Cast each level to a Dictionary as you parse. Make sure to still check if optional values exist.

    var response = Dictionary()
    
    func valueForCurrency(currency :String, exchange :String) -> Float? {
        let exchanges = response["current_rates"] as? Dictionary
    
        let currencies = exchanges?[exchange] as? Dictionary
    
        return currencies?[currency] as? Float
    }
    

提交回复
热议问题