swift - 根据键从字典数组中获取元素

标签 swift

我有像[[:String:Any]]这样的数组

我有一个 value string ,我想提取具有该键的元素无需循环(一行)。

为了检查它是否在那里,我使用了这个:

 if(array.map{$0["NAME"] as! String}.contains(value)){

有没有办法在 这个 if 语句中提取这个字典?

最佳答案

为此,无需映射 数组。您可以使用 contains(where:)

if array.contains(where: { $0["name"] as? String == value }) {
    print("Exist")
}

如果你想要数组中的对象(字典)也可以使用 first(where:)

if let dict = array.first(where: { $0["name"] as? String == value }) {
    print(dict)
}

有关 first(where:) 的更多信息,请查看 SO Thread

关于swift - 根据键从字典数组中获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43522346/

相关文章:

swift - For-in 循环走得太远,在展开时发现 'nil'

UITabBarController 上的快速 float 按钮

ios - 为什么每当我加载 UIImagePickerController View 时都会加载我的键盘?

ios - 如何快速查找 UIImage 中单个像素的颜色

ios - 在协议(protocol)方法的参数中使用默认值时出错

ios - 以编程方式动态居中 2 行文本,每行长度大致相等

ios - 我应该将什么传递给 `Result<Void, Error>` 的 .success() ?

ios - 在选项卡栏 Controller 中嵌入 View Controller 会删除导航项

swift - 快速停止 block 文字的任何方法

swift - 在 HalfSizePresentationController 类中展开时意外发现 nil