Error with APAddressBOOK: "fatal error: Array index out of range"
Error with APAddressBOOK: "fatal error: Array index out of range"
每次我在 Swift 中处理地址簿(通过 cocapods 使用 APAddressBOOK)时我都会收到这个奇怪的错误,经过一些调试后我发现了空对象 (没有记录数组中的 phone number) 会导致此问题,但我不确定如何摆脱它。
这是我的代码:
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 " "
}
有什么线索吗?
Array
的下标不是 return 指示索引是否超出数组范围的可选值;相反,您的程序将崩溃并显示消息“致命错误:数组索引超出范围”。应用此代码:当 contactno
为空时,您的程序将崩溃,因为数组的索引 0 处没有元素。
解决问题的最简单方法可能是在 Array
上使用 first
属性。 first
将 return 数组中的第一个元素,或者 nil
如果数组为空。看一下 first
是如何声明的:
extension Array {
var first: T? { get }
}
从 Swift 2 开始,first
已成为 CollectionType
协议的扩展:
extension CollectionType {
var first: Self.Generator.Element? { get }
}
你可以这样使用:
if let numberRaw = contactno.phones?.first as? String {
// ...
}
每次我在 Swift 中处理地址簿(通过 cocapods 使用 APAddressBOOK)时我都会收到这个奇怪的错误,经过一些调试后我发现了空对象 (没有记录数组中的 phone number) 会导致此问题,但我不确定如何摆脱它。
这是我的代码:
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 " "
}
有什么线索吗?
Array
的下标不是 return 指示索引是否超出数组范围的可选值;相反,您的程序将崩溃并显示消息“致命错误:数组索引超出范围”。应用此代码:当 contactno
为空时,您的程序将崩溃,因为数组的索引 0 处没有元素。
解决问题的最简单方法可能是在 Array
上使用 first
属性。 first
将 return 数组中的第一个元素,或者 nil
如果数组为空。看一下 first
是如何声明的:
extension Array {
var first: T? { get }
}
从 Swift 2 开始,first
已成为 CollectionType
协议的扩展:
extension CollectionType {
var first: Self.Generator.Element? { get }
}
你可以这样使用:
if let numberRaw = contactno.phones?.first as? String {
// ...
}