我想要做的是每次调用函数时都能逐个从数组中返回项目,直到返回数组中的所有项目,然后再从第一项开始。
下面的代码正是我所需要的,但我觉得有一种更简单的方法可以做到这一点,我觉得这样做很奇怪。
以下代码的任何改进?
var fruits = ["Apple","Banana","blue","Orange"]
func fruit() -> String {
let removedFruit = fruits.removeAtIndex(0)
fruits.insert(removedFruit, atIndex:fruits.count)
return removedFruit
}
// the out put here is exactly what I need
// return Apple the first time the fruit function is called
// then return Banana the second time the function is called and so on...
print(fruit()) // Apple
print(fruit()) // Banana
print(fruit()) // Watermelon
print(fruit()) // Orange
// once all of the items in the array have been returned
// start again with the first item
print(fruit()) // Apple
print(fruit()) // Banana
print(fruit()) // Watermelon
print(fruit()) // Orange
答案 0 :(得分:2)
不要改变阵列,它很昂贵。
class FruitGenerator {
let fruits = ["Apple", "Banana", "Poop"]
var nextItemIndex = 0 // holds the index of item to be returned upon the next call to fruit()
func fruit() -> String {
let result = fruits[nextItemIndex]
nextItemIndex = (nextItemIndex + 1) % fruits.count
return result
}
}
答案 1 :(得分:-2)
蛋糕的和平(代码编辑为功能齐全):
var fruits = ["Apple","Banana","blue","Orange"]
var index = 0
func fruit() -> String {
let ret = fruits[index]
(index == (fruits.count-1) ? (index=0) : (index=index+1))
return ret
}
这里的想法是保持对当前索引的引用。 使用第三个运算符来检查我们是否在数组的末尾,如果是这样我们重置索引,否则我们增加它。 请注意,您可能必须在运算符周围使用括号。