Map SwiftyJSON to array
Asked Answered
U

2

5
let json = JSON(response.result.value!)

let things = json.array.map { jsonThing in          
   Thing()                    
}!

json.array returns an array of one hundred JSONs. After the call to map, I end up with a single Thing.

Why don't I have a new array of Things?

Underprivileged answered 27/10, 2015 at 16:8 Comment(0)
T
6

SwiftyJSON has two kinds of getters: optional and non-optional.

The non-optional getters have the "...Value" name syntax.

Optional:

json.array

Non-optional:

json.arrayValue

Be careful, though: if you're using the non-optional getters with a nil value it will crash. If the value can be nil it's better to use the optional getter and safely unwrap with if let (optional binding) or any other known technique: optional chaining, nil coalescing, etc.

Tatterdemalion answered 27/10, 2015 at 16:44 Comment(0)
P
2

Because json.arrayreturns [JSON]?, not [JSON]

Thus you have called .map on a single instance of Optional<[JSON]> rather than an Array<JSON> as you were expecting.

You need to call:

json.array?.map ...

Possessed answered 27/10, 2015 at 16:41 Comment(1)
Great explanation but not quite as comprehensive as Eric D's. ;)Underprivileged

© 2022 - 2024 — McMap. All rights reserved.