1

I am using GKRandomSource in a struct to return a random inspirational quote in the view. Is there a way to return that random number and omit the prior entry? That way the user doesn't receive the same quote twice in a row.

let inspiration = [
    "You are looking rather nice today, as always.",
    "Hello gorgeous!",
    "You rock, don't ever change!",
    "Your hair is looking on fleek today!",
    "That smile.",
    "Somebody woke up on the right side of bed!"]

func getRandomInspiration() -> String {
    let randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(inspiration.count)
    return inspiration[randomNumber]
}
Confused
  • 6,048
  • 6
  • 34
  • 75
VegaStudios
  • 378
  • 1
  • 4
  • 22
  • best to have a copy of the array and every time you take a random index, you remove it from the array and then random from 0 to the new arrays size – Fonix Oct 03 '16 at 03:16

1 Answers1

2

To keep from generating the same quote, keep track of the last one in a struct property called lastQuote. Then reduce the max random number by 1, and if you generate the same as the lastQuote, use max instead.

struct RandomQuote {
    let inspiration = [
        "You are looking rather nice today, as always.",
        "Hello gorgeous!",
        "You rock, don't ever change!",
        "Your hair is looking on fleek today!",
        "That smile.",
        "Somebody woke up on the right side of bed!"]

    var lastQuote = 0

    mutating func getRandomInspiration() -> String {
        let max = inspiration.count - 1
        // Swift 3
        // var randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: max)
        var randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(max)
        if randomNumber == lastQuote {
            randomNumber = max
        }
        lastQuote = randomNumber
        return inspiration[randomNumber]
    }
}

var rq = RandomQuote()
for _ in 1...10 {
    print(rq.getRandomInspiration())
}
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • Thanks for the response; `for _ in 1...10` can't be passed at the top level. Is there something I have to fix there? (starting out in swift) – VegaStudios Oct 03 '16 at 04:05
  • That's just a demo of how to use the RandomQuote structure. You can add the var rq=RandomQuote() as a property of a class such as a ViewController and the call rq.getRandomInspiration() inside of any function in that VC to get a quote. – vacawama Oct 03 '16 at 04:10