Filtering a json object using Swift's Map api and Objective-c's valueForKeyPath -


given http://jsonplaceholder.typicode.com/users

for simplicity here abridged version of json

var userdict: [[string, string]]?  <-- string json converts foundation , saved here  // json [{   "address" : {     "geo" : {       "lat" : "-37.3159"     }   } }] 

i trying array of lat latitude of of geographical point of address. have 2 choices, swift or objective-c

i can array of lat using old valueforkeypath: method

var keypathlatitude: [string] = (userdict! nsarray).valueforkeypath("address.geo.lat") as! [string] // objective-c api 

which give me ["-37.3159"] array 1 element. having difficulty doing swift's map api

var maplatitude: [string] = userdict!.map({$0["address"]?["geo"]["lat"] as! string}) // <-- not this.  want ["-37.3159"] result. 

update

var maplatitude: [string] = userdict!.map({$0["address"]?["geo"]??["lat"] as! string}) 

using mattdaw's suggestion added '?'. did not work. oddly enough, when added '??' appears work desired. .... why? '??' nil coalescing operator not?

btw, i'm doing playgrounds

with pure swift objects, optional chaining works:

let users = [ [ "address": [ "geo": [ "lat": "-37.3159" ] ] ] ] let lats = users.map { $0["address"]?["geo"]?["lat"] } println(lats) 

... when you're dealing result of parsing json through nsjsonserialization, gets ugly. check out swiftyjson (https://github.com/lingoer/swiftyjson) more background.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -