Error with APAddressBOOK: "fatal error: Array index out of range"

147 views Asked by At

I am receiving this strange error every time I process an address book ( using APAddressBOOK via cocapods) in Swift and after some debugging I found out that and empty object (record with no phone number) within the array causes this issue but am not sure how to get rid of it.

Here is my code:

func getPersonsNo(contactno: AnyObject) -> String {
    println(contactno) // **when the object is empty I get this "[]"**
            if let numberRaw = contactno.phones?[0] as? String { // at this statement the program crashes with a fatal error 
        println(numberRaw)
        return numberRaw)
    }

    return " "
}

Any clues what is happening here?

1

There are 1 answers

4
ABakerSmith On BEST ANSWER

The subscript of an Array doesn't return an optional to indicate if an index is out of range of the array; instead your program will crash with the message “fatal error: Array index out of range”. Applying this your code: when contactno is empty your program will crash because there's no element at index 0 of the array.

To easiest way to solve your problem is probably to use the first property on Array. first will return the first element in the array, or nil if the array is empty. Taking a look at how first is declared:

extension Array {
    var first: T? { get }
}

As of Swift 2, first has been made an extension of the CollectionType protocol:

extension CollectionType {
    var first: Self.Generator.Element? { get }
}

You'd use this like so:

if let numberRaw = contactno.phones?.first as? String { 
    // ...
}