我想在aSet<ShopItemCategory>
中获取下一个项目。我想我可以将当前项的索引作为Int
获取,然后使用该索引通过向其添加1来获取同一集合中的下一个项(除非它是集合中的最后一个项,否则索引将设置为0)。但是,indexof没有为我返回Int
。它返回类型SetIndex<ShopItemCategory>
。如何返回类型Int
索引,或者以其他更简单的方式一次循环一个set by 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
s本质上是无序的。使用迭代器,您可以在每个元素中工作,但访问顺序不能保证。如果需要有序集合,请使用数组。
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.
关于swift - 获取Swift Set中的下一项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32545183/