gpt4 book ai didi

Swift 中的字典访问

转载 作者:IT王子 更新时间:2023-10-29 05:29:04 26 4
gpt4 key购买 nike

考虑以下从 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

查找书名的正确方法是什么?

最佳答案

您可以使用 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

关于Swift 中的字典访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24705106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com