Reputation: 15
I'm experimenting with dictionaries in Swift 4. I'm trying to make an array from a couple of values belonging to a randomly picked key within a dictionary. I'm not exactly sure how I need to do this in Swift 4.
//: Dictionary Test
import UIKit
var database = ["Albert Einstein": ["Alberts first quote",
"Alberts second quote",
"Alberts third quote"],
"Martin Luther King": ["Martin's first quote",
"Martin's second quote",
"Martin's third quote"],
"Newton": ["Newton's first quote",
"Newton's second quote",
"Newton's third quote"]]
func randomQuote(){
//Make an array from database keys
var authorArray = Array(database.keys)
//Pick a random author
let author = (authorArray[Int(arc4random_uniform(UInt32(authorArray.count)))])
//Make an array from values based on the author we've picked (HERE'S THE PROBLEM)
let quoteArray = Array(database[author].values)
//Pick a random quote from the choses author
let quote = (quoteArray[Int(arc4random_uniform(UInt32(quoteArray.count)))])
print(author)
print(quote)
}
randomQuote()
Now obviously let quoteArray = Array(database[author].values)
is not working. Anyone an idea how this would work?
Upvotes: 0
Views: 531
Reputation: 318824
There's lots of little things in randomQuote
that need to be fixed.
There's no need for the 2nd use of Array(...)
.
And database[someKey]
already gives you the array of quotes.
You also have some extra sets of parentheses you don't need.
Here's the updated code with all the fixes:
func randomQuote(){
//Make an array from database keys
var authorArray = Array(database.keys)
//Pick a random author
let author = authorArray[Int(arc4random_uniform(UInt32(authorArray.count)))]
//Make an array from values based on the author we've picked
let quoteArray = database[author]!
//Pick a random quote from the choses author
let quote = quoteArray[Int(arc4random_uniform(UInt32(quoteArray.count)))]
print(author)
print(quote)
}
Upvotes: 1
Reputation: 7746
database[author] is an array, not a dictionary. you need to do:
let quoteArray = database[author]!
Side note: surrounding things in parens when unnecessary is confusing as it make it look like a tuple.
Upvotes: 0