0

I have a class for quotes that contains an array full of quotes. The code below shows two. Each quote has an author, attribution, and Bools for hasSeen and hasSaved.

I want to show one random quote at a time. When the user refreshes the screen, they get another quote. When I put .randomElement()! on the array and print the results, I get appName.Quote.

Is there a way to access a random quote from this array? I want to be able to show the text and attribution to the end user.

var quotes:[Quote] = [
    Quote(
        quoteText: "The only way to make sense out of change is to plunge into it, move with it, and join the dance.",
        quoteAttribution: "Alan Watts",
        hasSeen: false,
        hasSaved: false),
    Quote(
        quoteText: "Luck is what happens when preparation meets opportunity.",
        quoteAttribution: "Seneca",
        hasSeen: false,
        hasSaved: false)
]
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    FYI - you should not be putting all of that data in code. Store it in a file or database and load what you need at runtime. – rmaddy Jun 11 '18 at 01:58

1 Answers1

1

You can extend swift's Array to have this feature:

extension Array {
    func randomItem() -> Element? {
        if isEmpty { return nil }
        let index = Int(arc4random_uniform(UInt32(self.count)))
        return self[index]
    }
}

And you access random Quote like this:

let quote = quotes.randomItem()

On a side note, since you are dealing with fixed/staitc content/structure, consider using tuple for storing Quote

Sunil
  • 728
  • 5
  • 7