Sebastian Hubard
Sebastian Hubard

Reputation: 163

Swift: Writing code that will call random item from array and not call that item again

I'm writing a basic truth or dare app as a practice project and I'm running into an issue when I try to make an array for truths/dares. I want to randomly call a dare but not have that dare be available as an option when I call the method again. I tried using array.remove(at: ) but I then run into issues with immutable classes/methods.

Any help would be appreciated.

var wildDares = [
    "Wild Dare A",
    "Wild Dare B",
    "Wild Dare C",
    "Wild Dare D",
    "Wild Dare E"]

func randomWildDare() -> String {
    let randomNum = GKRandomSource.sharedRandom().nextInt(upperBound: wildDares.count)

    if wildDares.count == 1 {
        return "You're out of dares. Select a new pack or click 'New Game' in the menu section." } else {
            //wildDares.remove(at: randomNum)
            return wildDares[randomNum]
    }
}

Upvotes: 0

Views: 75

Answers (1)

magnuskahr
magnuskahr

Reputation: 1320

I see you are using GameplayKit to shuffle your dares, but shuffle is built in to swift itself now.

struct DareStore {
    private var dares: [String]
    init(dares: [String]) {
        self.dares = dares.shuffled()
    }

    mutating func next() -> String? {
        if dares.count > 0 {
            return dares.removeFirst()
        }
        return nil
    }
}

In this DareStore you see we provide the init with an array of dares, and we there handle shuffling of it. Now whenever next() is called, it will just remove and return the first of the shuffled dares, until no more are left.

var dares = DareStore(dares: ["1", "2", "3"])
while let dare = dares.next() {
    print(dare)
}

Upvotes: 1

Related Questions