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?
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: whencontactno
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 onArray
.first
will return the first element in the array, ornil
if the array is empty. Taking a look at howfirst
is declared:As of Swift 2,
first
has been made an extension of theCollectionType
protocol:You'd use this like so: