Thripthi Haridas
Thripthi Haridas

Reputation: 363

Swift get value from Dictionary

please help me to get values from response

{
  "BU": {
    "name": "Bulawayo",
    "names": "Bulawayo"
  },
  "HA": {
    "name": "Harare",
    "names": "Harare"
  }
}

i want value of key name. my code is below

let response = responseObject as! Dictionary<String,AnyObject>
let stateNames = response.values as! Dictionary<String,AnyObject>

getting this issue:

cannot cast from lazyMapCollection<Dictionary<String,Anyobject>,String> in swift

Upvotes: 0

Views: 4130

Answers (3)

Nirav D
Nirav D

Reputation: 72460

If you want all the name then try like this

var name = [String]()
let keyArray = responseDic.allKeys as! [String]
for key in keyArray {
    let nameDic = responseDic.valueForKey(key) as! Dictionary<String,AnyObject>
    name.append(nameDic.valueForKey("name") as! String)
}

Upvotes: 3

Sreehari
Sreehari

Reputation: 1

You could do the following to access the values:

if let responseBU = response["BU"] {
   let name = responseBU["name"]
   let names = responseBU["names"] 
}

Upvotes: 0

Bhautik Ziniya
Bhautik Ziniya

Reputation: 1564

you can get the value of "BU" asresponse.valueForKey("BU").valueForKey("name") it will give you the value "Bulawayo".

Upvotes: 3

Related Questions