3 回答

TA貢獻1719條經(jīng)驗 獲得超6個贊
斯威夫特的錯誤處理(do/ try/ catch)是不是要解決運行時異常,如“索引超出范圍”。
運行時異常(您可能還會看到稱為trap,致命錯誤,斷言失敗等)是程序員錯誤的標(biāo)志。除了內(nèi)部-Ounchecked版本,Swift通常保證這些會使您的程序崩潰,而不是繼續(xù)在錯誤/未定義狀態(tài)下執(zhí)行。這類崩潰可能是由于強制展開!,隱式展開,unowned引用濫用,溢出,fatalError()s和precondition()s及assert()s等導(dǎo)致的整數(shù)運算/轉(zhuǎn)換(以及不幸的是,Objective-C異常)引起的。
解決方法是簡單地避免這些情況。在您的情況下,檢查數(shù)組的邊界:
if indexPath.section < msgSections.count && indexPath.row < msgSections[indexPath.section].msg.count {
let msg = msgSections[indexPath.section].msg[indexPath.row]
// ...
}
(或者,正如rmaddy在評論中說的那樣-調(diào)查為什么會發(fā)生此問題!它根本不應(yīng)該發(fā)生。)

TA貢獻1875條經(jīng)驗 獲得超3個贊
斯威夫特4:
extension Collection where Indices.Iterator.Element == Index {
subscript (exist index: Index) -> Iterator.Element? {
return indices.contains(index) ? self[index] : nil
}
}
用法:
var index :Int = 6 // or whatever number you need
if let _ = myArray[exist: index] {
// do stuff
}
要么
var index :Int = 6 // or whatever number you need
guard let _ = myArray[exist: index] else { return }
- 3 回答
- 0 關(guān)注
- 822 瀏覽
添加回答
舉報