Arrays 逐个返回数组中的项目,直到所有项目都已返回,然后重新开始
我想做的是,每次调用函数时都能从数组中逐个返回项,直到数组中的所有项都已返回为止,然后从第一项重新开始 下面的代码正是我所需要的,但我觉得有一种更简单的方法可以做到这一点,我只是觉得我这样做很奇怪 下面的代码有什么改进吗Arrays 逐个返回数组中的项目,直到所有项目都已返回,然后重新开始,arrays,swift,Arrays,Swift,我想做的是,每次调用函数时都能从数组中逐个返回项,直到数组中的所有项都已返回为止,然后从第一项重新开始 下面的代码正是我所需要的,但我觉得有一种更简单的方法可以做到这一点,我只是觉得我这样做很奇怪 下面的代码有什么改进吗 var fruits = ["Apple","Banana","blue","Orange"] func fruit() -> String { let removedFruit = fruits.removeAtIndex(0) fruits.in
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
}
}
使数组为常量,并为每个函数调用更新索引…这甚至不会编译。事实上,有人会对此进行投票,这确实令人不安…@thibautnoah它也不会编译,因为你的三元运算符行在语法上是错误的。你不应该使用三元运算符来产生副作用。虽然很容易修复:
i=(i==fruit.count-1)?0:i+1
@thibautnoah那么,编写伪代码比编写错误代码更好取决于谁在阅读,不管怎样,我编辑了代码,编译工作等等@Tamas Zahola-您的示例工作很好,谢谢。现在,我有一个问题。我目前正在学习OOP,我注意到您在示例中使用了一个类,我知道如果我愿意,我可以从类中提取代码,但我想知道,为像上述面向对象代码那样简单的东西创建类是否常见。同样,为简单的东西创建一个类是常见的吗?这就是您将如何构造代码的方式吗?取决于用例。但我肯定不会在任何地方使用全局数组,而是使用一个快速的游乐场。现在,假设您想在不同的数组上使用这种包装数组机制,而不仅仅是水果数组。在这种情况下,下一个逻辑步骤是在初始值设定项中传入数组,而不是对其进行硬编码。这样,你就可以把这个包数组概念封装在一个很好的、可测试的、自包含的类中。@ TAMAS ZaHOLA-<代码>但是我当然不会在任何地方使用一个全局数组,而是一个快速的游乐场。< /代码>如果我正确地理解了这一点,一个好的经验法则是考虑每次需要从数组中获取项时创建一个新类。字典等,为了符合MVC模式,我是对的吗?@fs_tigre如果需要跟踪某些状态(如本例中的nextItemIndex
),最好将其封装到对象中。虽然哪个状态变量属于同一个取决于您的问题域。
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
}
}