14

This won't compile: enter image description here I've tried a couple different things; different ways of declaring the Dictionary, changing its type to match the nested-ness of the data. I also tried explicitly saying my Any was a collection so it could be subscripted. No dice.

import UIKit


import Foundation

class CurrencyManager {

    var response = Dictionary<String,Any>()
    var symbols = []


    struct Static {
        static var token : dispatch_once_t = 0
        static var instance : CurrencyManager?
    }

    class var shared: CurrencyManager {
        dispatch_once(&Static.token) {  Static.instance = CurrencyManager() }
        return Static.instance!
    }

    init(){
        assert(Static.instance == nil, "Singleton already initialized!")
        getRates()

    }


    func defaultCurrency() -> String {

        let countryCode  = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as String
        let codesToCountries :Dictionary = [ "US":"USD" ]

        if let localCurrency = codesToCountries[countryCode]{
            return localCurrency
        }

        return "USD"

    }

    func updateBadgeCurrency() {

        let chanCurr = defaultCurrency()

        var currVal :Float = valueForCurrency(chanCurr, exchange: "Coinbase")!

        UIApplication.sharedApplication().applicationIconBadgeNumber = Int(currVal)

    }

    func getRates() {
        //Network code here
        valueForCurrency("", exchange: "")
    }

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


}
0

4 Answers 4

19

Let's take a look at

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

response is declared as Dictionary<String,Any>(), 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<String,Dictionary<String,Dictionary<String, Float>>>()

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<String,Any>()

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

    let currencies = exchanges?[exchange] as? Dictionary<String,Any>

    return currencies?[currency] as? Float
}
7
  • Any reason why this wouldn't work? let exchanges = response["current_rates"] as Dictionary?
    – rsmoz
    Jun 9, 2014 at 20:45
  • I get "Could not find an overload for subscript that accepts supplied arguments"
    – rsmoz
    Jun 9, 2014 at 20:46
  • I added a second solution. To use that method you just need to put the question mark after "as" instead of after "Dictionary"
    – Dash
    Jun 9, 2014 at 20:51
  • Any way of doing this without hardcoding nested types? (i.e. my comment to Alex's answer)
    – rsmoz
    Jun 9, 2014 at 20:52
  • 1
    Just add the element type: let symbols = response["symbols"] as? Array<ElementType>
    – Dash
    Jun 9, 2014 at 21:04
3

You can get nested dictionary data by following these steps:

let imageData: NSDictionary = userInfo["picture"]?["data"]? as NSDictionary
let profilePic = imageData["url"] as? String
2
func valueForCurrency(currency :String, exchange :String) -> Float? {
    if let exchanges = response["current_rates"] as? Dictionary<String,Any> {
        if let currencies = exchanges[exchange] as? Dictionary<String,Any> {
            return currencies[currency] as? Float
        }
    }
    return nil
}
1

response is declared as such:

var response = Dictionary<String,Any>()

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<String,Dictionary<String,Dictionary<String,Float>>>()
// ... populate dictionaries
println(response["current_rates"]?["a"]?["b"]) // The float
3
  • The problem is not all objects in the entire hierarchy follow those generics. Somewhere there may be an array, and I don't want to hardcode the entire interpretation of the JSON in this code.
    – rsmoz
    Jun 9, 2014 at 20:47
  • Then you will need to check types and cast things at runtime.
    – Alex Wayne
    Jun 9, 2014 at 20:50
  • The thing is, I know the specific types of the elements I want, and I'd like to ignore other ones. If I access ["current_rates"], I know I will always get a dictionary.
    – rsmoz
    Jun 9, 2014 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.