0

I am using SwiftyJSON to parse a JSON array and can't figure out why I can't use the values when parsing the array to populate a Dictionary.

var dictionary = [String: String]()
    for (index: String, subJson: JSON) in json[myArray] {
        let name = subJson["name"].string
        let value = subJson["value"].string
        gameOwned += [name: value]
    }

I am receiving this error on this line:

gameOwned += [name: value]

Am I adding it to the empty dictionary wrong? I have already tested the values of name and value and they println with no problems.

The Nomad
  • 7,155
  • 14
  • 65
  • 100

1 Answers1

0

I had the same problem with this code:

func authParam(withParams: [String: AnyObject?]) -> [String: AnyObject?] {
    var params: [String: AnyObject?] = ["user_nonce": self.user_nonce, "user_identifier": self.user_identifier];
    params += withParams; //Error

    return params;
}

I found out that concatenating two dictinaries with

var a = ["one": "a"]
a += ["two": "b"]

is wrong because this way you are concatenating two arrays not dictionaries - so swift is expecting an array with CGFloat as key.

I found a solution here at Stackoverflow. Just Extend the dictionary class and add a merge function

extension Dictionary {
    mutating func merge<K, V>(dict: [K: V]){
        for (k, v) in dict {
            self.updateValue(v as Value, forKey: k as Key)
        }
    }
}

so now i can merge my dictionaries without a lot of effort

func authParam(withParams: [String: AnyObject?]) -> [String: AnyObject?] {
    var params: [String: AnyObject?] = ["user_nonce": self.user_nonce, "user_identifier": self.user_identifier];

    params.merge(withParams); //works fine

    return params;
}
Community
  • 1
  • 1