少し探してみましたが、どうもお望みの動作の実現は難しそうです。Swiftの場合、fatal errorのような深刻なエラーはクラッシュさせるべき、という思想なのかもしれません。
ios - How do I catch "Index out of range" in Swift? - Stack Overflowには以下のようなコメントがありました。
※読みやすさを重視して、引用部分にオリジナルのコメントに似せたMarkdownを付加しました。
Swift's Error Handling (do/try/catch) is not the solution to runtime exceptions like "index out of range".
A runtime exception (you might also see these called trap, fatal error, assertion failure, etc.) is a sign of programmer error. Except in -Ounchecked
builds, Swift usually guarantees that these will crash your program, rather than continuing to execute in a bad/undefined state. These sorts of crashes can arise from force-unwrapping with !
, implicit unwrapping, misuse of unowned
references, integer operations/conversions which overflow, fatalError()
s and precondition()
s and assert()
s, etc. (And, unfortunately, Objective-C exceptions.)
The solution is to simply avoid these situations. In your case, check the bounds of the array:
if indexPath.section < msgSections.count && indexPath.row < msgSections[indexPath.section].msg.count {
let msg = msgSections[indexPath.section].msg[indexPath.row]
// ...
}
> (Or, as rmaddy says in comments — investigate **why** this problem is occurring! It really shouldn't happen at all.)
他サイトには以下のような記事もありました。こちらも設計上のご参考になるかもしれません。
[Swiftのエラー4分類が素晴らしすぎるのでみんなに知ってほしい - Qiita](http://qiita.com/koher/items/a7a12e7e18d2bb7d8c77)
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。