xyk blog

最近は iOS 開発の記事が多めです。

Array の indices を使って安全に添字アクセスする

検証環境:
Xcode 12.3
Swift 5.3.2

配列に添字アクセスする場合、存在しないインデックスにアクセスすると Index out of rangeの例外が発生してしまうので、事前にインデックスが配列数の範囲内であるかをチェックする必要がある。
そういう場合に Array#indices プロパティ-> Range#contains メソッドを使って範囲内のインデックスであるかチェックできる。

let ary = ["a", "b", "c"]
let index = 1

if ary.indices.contains(index) {
  let ret = ary[index]
} else {
  // Index out of range
}

安全に添字アクセスできる subscript を Extension として追加する例。

extension Array {
  subscript (safe index: Index) -> Element? {
    indices.contains(index) ? self[index] : nil
  }
}

let ary = ["a", "b", "c"]
ary[safe: 0] // "a"
ary[safe: 3] // nil