sol*_*eil 11 dictionary nsdictionary swift
请考虑以下代码,该代码从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]
Run Code Online (Sandbox Code Playgroud)
现在,我无法访问单个图书词典:
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
Run Code Online (Sandbox Code Playgroud)
找到这本书名称的正确方法是什么?
Ben*_*nzi 24
你可以使用Beta 3的Arrays和Dictionaries的新语法糖.
let path = NSBundle.mainBundle().pathForResource("books", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path)
let books = dict.objectForKey("Books")! as [[String:AnyObject]]
Run Code Online (Sandbox Code Playgroud)
您可以bookData按原样访问,自动类型推断应该工作...
let rnd = Int(arc4random_uniform((UInt32(books.count))))
let bookData = books[rnd]
Run Code Online (Sandbox Code Playgroud)
为书籍词典中的每个项目添加一个显式类型,因为我们已将其定义为AnyObject.
let title = bookData["title"]! as String
let numPages = bookData["pages"]! as Int
Run Code Online (Sandbox Code Playgroud)
晚编辑
使用nil合并运算符,??您可以检查nil值并提供如下的备用值:
let title = (bookData["title"] as? String) ?? "untitled"
let numPages = (bookData["pages"] as? Int) ?? -1
Run Code Online (Sandbox Code Playgroud)