【发布时间】:2014-07-11 19:26:20
【问题描述】:
考虑以下从 plist 中获取字典数组的代码:
let path = NSBundle.mainBundle().pathForResource("books", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path)
let books:Array = dict.objectForKey("Books") as Array<Dictionary<String, AnyObject>> //I hate how ugly and specific this is. There has got to be a better way??? Why can't I just say let books:Array = dict.objectForKey("Books")?
let rnd = Int(arc4random_uniform((UInt32(books.count))))
let bookData:Dictionary = books[rnd]
现在,我无法访问个别图书词典:
let title:String = bookData.objectForKey("title") //[String: AnyObject] does not have a member named 'objectForKey'
let title:String = bookData["title"] // (String, AnyObject) is not convertible to String
找到书名的正确方法是什么?
【问题讨论】:
-
你试过
let bookData:Dictionary<String,String> = books[rnd]吗?然后你的第二个访问器应该工作。 (我不在电脑前测试)
标签: dictionary swift nsdictionary