我有一系列词典:
let someArray = [["Andrew":"qwerty"],["Paul":"123456"],["Sarah":"123123"]]
我有一个我想在数组中找到的值
let search = "Sarah"
我想知道数组中是否存在值“Sarah”。我该怎么做?
答案 0 :(得分:3)
你有一系列词典。
您只需要搜索具有key == "Sarah"
所以
let elms = [["Andrew":"qwerty"],["Paul":"123456"],["Sarah":"123123"]]
let sarahDict = elms.first { $0.keys.contains("Sarah") }
然而,模型值会使代码更清晰
let elms = [["Andrew":"qwerty"],["Paul":"123456"],["Sarah":"123123"]]
struct Person {
let name: String
let value: String
init?(dict:[String:String]) {
guard let name = dict.keys.first, let value = dict[name] else { return nil }
self.name = name
self.value = value
}
}
let person = elms.compactMap(Person.init).first { $0.name == "Sarah" }