15
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】Index out of rangeを回避

Posted at

はじめに

業務でIndex out of rangeにならないように安全に要素を取得してあげたい!と思い、いろいろ調べた結果行きついたものを備忘録として残します。(ファイル名はてきとうです。。。)

Array.swift
var hoge = ["a", "b", "c", "d"]

hoge[3] //結果: d
hoge[4] //結果: Index out of range

これをどうやって防ぐのかというと、Arrayのsubscriptメソッドのsafeって言うのを使います。

ArraySubscriptSafe.swift
var hoge = ["a", "b", "c", "d"]

extension Array {
    subscript (safe index: Index) -> Element? {
        //indexが配列内なら要素を返し、配列外ならnilを返す(三項演算子)
        return indices.contains(index) ? self[index] : nil
    }
}

hoge[safe: 3] //結果: d
hoge[safe: 4] //結果: nil

まとめ

他にもやり方はいろいろとあると思うので、その度に更新していければと思います。
間違いなどがありましたら指摘お願いします。

参照

15
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?