gpt4 book ai didi

json - 在 Swift 2 中搜索字典对象数组

转载 作者:搜寻专家 更新时间:2023-11-01 06:18:50 25 4
gpt4 key购买 nike

我有一个从 JSON 文件填充的字典对象数组,定义为:

var peopleArray = [Person]()

Person 定义为:

class Person {

var name: String?
var gender: String?
var html_url: String?

init(json: NSDictionary) { // Dictionary object
self.name = json["name"] as? String
self.gender = json["gender"] as? String
self.html_url = json["html_url"] as? String // Location of the JSON file
}
}

填充数组后,我很难使用 contains 函数来确定是否存在具有特定 name 的人。

我被抛出以下错误:无法转换“字符串!”类型的值到预期的参数类型 '@noescape (Person) throws -> Bool' 我尝试了以下行:

if (peopleArray.contains("Bob"))

最佳答案

您应该使用闭包作为contains 调用的输入参数:

peopleArray.contains { person -> Bool in
person.name == "Bob"
}

或使用短样式语法:

peopleArray.contains { $0.name == "Bob" }

或者,如果您想要寻找特定的人,您可以使 Person 符合 Equatable:https://stackoverflow.com/a/32953118/2227743

关于json - 在 Swift 2 中搜索字典对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38354628/

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