gpt4 book ai didi

arrays - 一项一项地返回数组中的项目,直到返回所有项目,然后重新开始

转载 作者:行者123 更新时间:2023-11-30 13:43:46 25 4
gpt4 key购买 nike

我想要做的是每次调用函数时都能够从数组中逐个返回项目,直到返回数组中的所有项目,然后从第一个项目重新开始。

下面的代码完全满足了我的需要,但我觉得有一种更简单的方法可以做到这一点,只是感觉我的做法很奇怪。

下面的代码有什么改进吗?

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

最佳答案

不要改变数组,这很昂贵。

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
}
}

关于arrays - 一项一项地返回数组中的项目,直到返回所有项目,然后重新开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35225485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com