In my Swift app, I'm querying an api returning a json object like this :
{
key1: value1,
key2: value2,
array : [
{
id: 1,
string: "foobar"
},
{
id: 2,
string: "foobar"
}
]
}
Facts :
- The array value can be empty.
- I want to read the first array element, present or not.
In Swift i'm doing :
if let myArray: NSArray = data["array"] as? NSArray {
if let element: NSDictionary = myArray[0] as? NSDictionary {
if let string: NSString = element["string"] as? NSString {
// i should finally be able to do smth here,
// after all this crazy ifs wrapping
}
}
}
It works if the array and the first element exist, but i'm having a crash with "index 0 beyond bounds for empty array" even if the element assignment is within an if let wrapping.
What i am doing wrong here ? I'm getting crazy with Swift optionals, typing and crazy if let wrapping everywhere...