はじめに
やりたいことはタイトルの通りです。
1番前にいる時に前の要素を取得しようとすると、1番後ろの要素を取得したいです
1番後ろにいる時に前の要素を取得しようとすると、1番前の要素を取得したいです
実装
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")
func currentItemIndex(selected: XXX, in array: [XXX]) -> Int? {
if let index = array.firstIndex(where: { $0.id == selected.id }) {
return index
} else {
return nil
}
}
func previousItem(selected: XXX, in array: [XXX]) -> XXX? {
if let currentIndex = currentItemIndex(selected: selected, in: array) {
let nextIndex = (currentIndex + 1) % array.count
return array[nextIndex]
}
return nil
}
func nextItem(selected: XXX, in array: [XXX]) -> XXX? {
if let currentIndex = currentItemIndex(selected: selected, in: array) {
let previousIndex = (currentIndex - 1 + array.count) % array.count
return array[previousIndex]
}
return nil
}
print(nextItem(selected: selectedItem, in: array)) // XXX(id: "002")
print(previousItem(selected: selectedItem, in: array)) // XXX(id: "004")
前の要素を取得する
func previousItem(selected: XXX, in array: [XXX]) -> XXX? {
if let currentIndex = currentItemIndex(selected: selected, in: array) {
let nextIndex = (currentIndex + 1) % array.count
return array[nextIndex]
}
return nil
}
次の要素を取得する
func nextItem(selected: XXX, in array: [XXX]) -> XXX? {
if let currentIndex = currentItemIndex(selected: selected, in: array) {
let previousIndex = (currentIndex - 1 + array.count) % array.count
return array[previousIndex]
}
return nil
}
おわり
実現できました