Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJamie Barton
14,498 PointsArray of dictionaries in Swift
Hi
I'm trying to extend the FunFact app by changing the name to Quotes and adding authors to Quotes.
I'm unsure how to initialize the array with Dictionaries.
For example I'm trying to do the following:
var quotesArray: Dictionary<String, String> = [
[quote: "Quote", author: "Some Guy"]
]
func randomQuote() -> String {
return quotesArray[Int(arc4random_uniform(UInt32(quotesArray.count)))]
}
Can anyone help me get past this?
2 Answers
Stephen McMillan
iOS Development with Swift Techdegree Graduate 33,994 PointsTry something like this... ?
let firstQuote = ["author" : "John Appleseed", "quote" : "Insert something inspirational..."]
let secondQuote = ["author" : "Joe Bloggs", "quote" : "Insert something inspirational..."]
var quotesArray = [firstQuote, secondQuote]
No idea if this will work. It should :)
Jamie Barton
14,498 PointsI figured out the issue. I had the keys not wrapped in quotes.
As for the random function, I did the following which solved it:
func randomQuote() -> Dictionary<String, String> {
return quotesArray[Int(arc4random_uniform(UInt32(quotesArray.count)))]
}
Final result:
var quotesArray = [
["quote": "Some text here", "author": "Some guy"],
["quote": "Some text here", "author": "Some guy"],
["quote": "Some text here", "author": "Some guy"]
]
Thanks :)