0
1

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.

iOS強化月間 - iOSアプリ開発の知見を共有しよう -

【Swift】特定の要素の次の要素、前の要素を取得する

Posted at

はじめに

やりたいことはタイトルの通りです。
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
}

おわり

実現できました

0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?