获取 Swift 集中的下一项

Get Next Item in Swift Set

我想获取 Set<ShopItemCategory> 中的下一项。我想我可以将当​​前项目的索引作为 Int ,然后使用该索引通过向其添加 1 来获取同一集合中的下一个项目(除非它是集合中的最后一个项目,然后索引将设置为 0)。但是,indexOf 对我来说不是 returning Int。它是 returning 类型 SetIndex<ShopItemCategory>。如何以其他更简单的方式 return 类型 Int 索引,或一次按 1 项循环集合?

mutating func swapCategory() {
    var categoryIndex =
        self.allShopItemCategories.indexOf(self.currentShopItemCategory)
    if categoryIndex == self.allShopItemCategories.count - 1 {
        categoryIndex = 0
    } else {
        categoryIndex++
    }
    self.currentShopItemCategory = self.allShopItemCategories[catIndex!]

}

您可以在集合上调用 enumerate() 以获得迭代器,但要意识到 Set 本质上是无序的。使用迭代器,您可以按自己的方式遍历每个元素,但不能保证访问顺序。如果你想要一个有序的集合,使用数组。

var x = Set<Int>()

x.insert(1)
x.insert(2)

for (index, item) in x.enumerate() {
    print("\(item)")
}

// the for loop could print "1,2" or "2,1"...
// there's no way to tell what order the items will be iterated over,
// only that each item *will* be iterated over.

你不能。因为 Set 中的元素没有排序。

另一方面,您可以从您的 Set 构建一个 Array 并根据需要访问元素。

看下面的例子:

class Foo<T:Hashable> {
    private let list: [T]
    private var currentIndex = 0
    var nextElm : T {
        currentIndex = (currentIndex + 1) % list.count
        return list[currentIndex]
    }
    init(set: Set<T>) {
        list = Array(set)
    }
}

let set : Set = [1,2,3]
let foo = Foo(set: set)

foo.nextElm // 3
foo.nextElm // 2
foo.nextElm // 1
foo.nextElm // 3
foo.nextElm // 2
foo.nextElm // 1

希望对您有所帮助。