0

I have an array of fruits. I am fetching a fruit randomly (see following codes). Question: How do I remove this fruit from the array after fetching it?

let fruits = ["apple", "orange", "banana", "pineapple", "lemon" ]

func getRandomFruit() -> String {
    let randomFruit = fruits.randomElement()!
    return randomFruit
}
Machavity
  • 30,841
  • 27
  • 92
  • 100
abacaba
  • 133
  • 1
  • 2
  • 9

2 Answers2

4

Do it just like a deck of cards. Instead of randomElement use shuffle and just remove the last element.

var fruits = ["apple", "orange", "banana", "pineapple", "lemon" ]
fruits.shuffle()
let myfruit = fruits.popLast()

(Just keep doing that as needed. myfruit will be nil if you've emptied the list.)

matt
  • 515,959
  • 87
  • 875
  • 1,141
2

No need to shuffle the whole collection to remove an element. Just get a random index, return that element and defer the removal of that element:

func getRandomFruit() -> String? {
    guard let index = fruits.indices.randomElement() else {
        return nil
    }
    defer { fruits.remove(at: index) }
    return fruits[index]
}

var fruits = ["apple", "orange", "banana", "pineapple", "lemon" ]

let fruit1 = getRandomFruit()   // apple
let fruit2 = getRandomFruit()   // lemon
let fruit3 = getRandomFruit()   // banana
let fruit4 = getRandomFruit()   // orange
let fruit5 = getRandomFruit()   // pineapple
let fruit6 = getRandomFruit()   // nil
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571