swift - Return items in an array one by one until all items have been returned then start again -
what want able return items array 1 one each time function called until of items in array have been returned, start again first item.
the code below need feel there simpler way this, feels weird how did it.
any improvements code below?
var fruits = ["apple","banana","blue","orange"] func fruit() -> string { let removedfruit = fruits.removeatindex(0) fruits.insert(removedfruit, atindex:fruits.count) return removedfruit } // out put here need // return apple first time fruit function called // return banana second time function called , on... print(fruit()) // apple print(fruit()) // banana print(fruit()) // watermelon print(fruit()) // orange // once of items in array have been returned // start again first item print(fruit()) // apple print(fruit()) // banana print(fruit()) // watermelon print(fruit()) // orange
don't mutate array, it's expensive.
class fruitgenerator { let fruits = ["apple", "banana", "poop"] var nextitemindex = 0 // holds index of item returned upon next call fruit() func fruit() -> string { let result = fruits[nextitemindex] nextitemindex = (nextitemindex + 1) % fruits.count return result } }
Comments
Post a Comment