【问题标题】:Dictionary access in SwiftSwift 中的字典访问
【发布时间】: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&lt;String,String&gt; = books[rnd]吗?然后你的第二个访问器应该工作。 (我不在电脑前测试)

标签: dictionary swift nsdictionary


【解决方案1】:

您可以将新的语法糖用于 Beta 3 中的数组和字典。

let path = NSBundle.mainBundle().pathForResource("books", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path)
let books = dict.objectForKey("Books")! as [[String:AnyObject]]

您可以按原样访问bookData,自动类型推断应该可以工作...

let rnd = Int(arc4random_uniform((UInt32(books.count))))
let bookData = books[rnd]

为 book 字典中的每个项目设置一个显式类型,因为我们已将其定义为 AnyObject。

let title = bookData["title"]! as String
let numPages = bookData["pages"]! as Int

后期编辑

  • 使用 nil 合并运算符 ??,您可以检查 nil 值并提供替代值,如下所示:

    let title = (bookData["title"] as? String) ?? "untitled"
    let numPages = (bookData["pages"] as? Int) ?? -1
    

【讨论】:

  • 我还是得到(String, AnyObject) is not convertible to String在线let title = bookData["title"]! as String
  • 你看过“title”里面的内容了吗?它的值也是一个对象吗?
  • 抱歉,错误消失了。 Beta3 对我来说仍然很麻烦。我会将此标记为正确。还有一个问题——为什么是“!”在 bookData["title"] 之后?
  • 说可选肯定是有值的。我认为这叫做强制展开之类的。
【解决方案2】:

斯威夫特:

如果使用Dictionary:

if let bookData = bookData{
   if let keyUnwrapped = bookData["title"]{
      title = keyUnwrapped.string
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 2016-10-13
    相关资源
    最近更新 更多