はじめに
要素が配列の何番目に出現するかを調べる方法を記事にしておきます
実装
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
は覚えておきたいです