0
2

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 1 year has passed since last update.

【Swift】特定の要素が配列の何番目に入っているかを知りたい

Posted at

はじめに

要素が配列の何番目に出現するかを調べる方法を記事にしておきます

実装

struct XXX {
    let id: String
}

let array: [XXX] = [XXX(id: "000"), XXX(id: "001"), XXX(id: "002"), XXX(id: "003"), XXX(id: "004")]

let selectedItem = XXX(id: "003")

// `firstIndex`を使用することでIndexを調べることができる
if let index = array.firstIndex(where: { $0.id == selectedItem.id }) {
    print("`selectedItem`は配列の\(index)番目の要素です。")
} else {
    print("`selectedItem`は配列に存在しません。")
}

おわり

firstIndexは覚えておきたいです

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?