Currently we have 2 arrays:
fileprivate var totalDrinksArray: [CocktailModel] = []
fileprivate var currentDrinksArray: [CocktailModel] = []
What I'm trying to do is get the first 2 objects of the totalDrinksArray
and add them to the currentDrinksArray
. After a button is pressed the next 2 drinks will be added from the totalDrinksArray
to the currentDrinksArray
(for a total of 4 drinks )and so on.
You can "add" arrays together:
currentDrinksArray += totalDrinksArray[0...1]
should work.
Not quite clear from your question, but if you want to "add the next two" (the 3rd and 4th):
currentDrinksArray += totalDrinksArray[2...3]
You can use Array method func prefix(_ maxLength: Int)
which will return a slice of the total array (up to n elements) or less if there is not enough elements and append the contents to your current array or insert it at the desired index:
currentDrinksArray.append(contentsOf: totalDrinksArray.prefix(2))
Or if you would like to insert them in the beginning of your array:
currentDrinksArray.insert(contentsOf: totalDrinksArray.prefix(2), at: 0)
Simplest safe solution IMO:
var currentIndex = 0
func addDrinks() {
if(currentIndex + 2 >= totalDrinksArray.count) {
currentDrinksArray += totalDrinksArray[currentIndex...]
}
else {
currentDrinksArray += totalDrinksArray[currentIndex..<(currentIndex + 2)]
}
currentIndex += 2
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.