Alex的回答为该问题提供了很好的建议和解决方案,但是,我偶然发现了一种更好的实现此功能的方法:
Swift 3.2及更高版本
extension Collection { /// Returns the element at the specified index if it is within bounds, otherwise nil. subscript (safe index: Index) -> Element? { return indices.contains(index) ? self[index] : nil }}Swift 3.0和3.1
extension Collection where Indices.Iterator.Element == Index { /// Returns the element at the specified index if it is within bounds, otherwise nil. subscript (safe index: Index) -> Generator.Element? { return indices.contains(index) ? self[index] : nil }}感谢Hamish提出了Swift 3解决方案。
迅捷2
extension CollectionType { /// Returns the element at the specified index if it is within bounds, otherwise nil. subscript (safe index: Index) -> Generator.Element? { return indices.contains(index) ? self[index] : nil }}例
let array = [1, 2, 3]for index in -20...20 { if let item = array[safe: index] { print(item) }}


