Reputation: 2453
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 :
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...
Upvotes: 0
Views: 4034
Reputation: 51911
The error is not concerning about Optional
. If you use subscription([]
) for array, you have to check the length of that.
if let myArray: NSArray = data["array"] as? NSArray {
if myArray.count > 0 { // <- HERE
if let element: NSDictionary = myArray[0] as? NSDictionary {
if let string: NSString = element["string"] as? NSString {
println(string)
}
}
}
}
But we have handy .firstObject
property
The first object in the array. (read-only)
If the array is empty, returns nil.
Using this:
if let myArray: NSArray = data["array"] as? NSArray {
if let element: NSDictionary = myArray.firstObject as? NSDictionary {
if let string: NSString = element["string"] as? NSString {
println(string)
}
}
}
And, we can use "Optional Chaining" syntax:
if let str = (data["array"]?.firstObject)?["string"] as? NSString {
println(str)
}
Upvotes: 1
Reputation: 36313
You can use this
var a = [Any?]()
a.append(nil)
If you have a non-optional array with AnyObject
you can use NSNull
(like in Obj-C)
Upvotes: 1