0

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...

2 Answers 2

1

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was having difficulties to understand all of that. This answer is well detailed and clear. Thanks, it helps me a lot.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.