Dictionary access in Swift
You could use the new syntactic sugars for Arrays and Dictionaries from Beta 3.
let path = NSBundle.mainBundle().pathForResource("books", ofType: "plist")let dict = NSDictionary(contentsOfFile: path)let books = dict.objectForKey("Books")! as [[String:AnyObject]]
You can access bookData
as is, automatic type inference should work...
let rnd = Int(arc4random_uniform((UInt32(books.count))))let bookData = books[rnd]
Put an explicit type for each item in the book dictionary, since we have defined it as AnyObject
.
let title = bookData["title"]! as Stringlet numPages = bookData["pages"]! as Int
Late edit
With the nil coalescing operator
??
you can check for nil values and provide an alternate value like so:let title = (bookData["title"] as? String) ?? "untitled"let numPages = (bookData["pages"] as? Int) ?? -1
Swift:
If using Dictionary
:
if let bookData = bookData{ if let keyUnwrapped = bookData["title"]{ title = keyUnwrapped.string }}