【问题标题】:Search key value in NSDictionary array swift [closed]快速搜索NSDictionary数组中的键值[关闭]
【发布时间】:2016-11-04 16:33:51
【问题描述】:

您好,我有一个Array,它有 NSDictionaries。

1st object->["111":title of the video]
2nd object->["123":title of the other]
3rd object->["133":title of  another]

假设我要搜索123 键入这个Array 并获取它的值。我该怎么做? 请帮我。 谢谢

更新

var subCatTitles=[AnyObject]()
let dict=[catData![0]:catData![4]]
self.subCatTitles.append(dict)

【问题讨论】:

标签: ios arrays swift search nsdictionary


【解决方案1】:

如果你的意思是你有一个这样的数组:

var anArray: [NSDictionary] = [
    ["111": "title of the video"],
    ["123": "title of the other"],
    ["133": "title of another"]
]

这将起作用:

if let result = anArray.flatMap({$0["123"]}).first {
    print(result) //->title of the other
} else {
    print("no result")
}

(我假设“重复优先”策略。)

但我强烈怀疑这种数据结构是否真的适合您的目的。

【讨论】:

  • 而不是 NSDictionary ,您可以使用 [[String:String]] 来获得纯 swift :)
【解决方案2】:

起初,字典不是数组......

import Foundation
// it is better to use native swift dictionary, i use NSDictionary as you request
var d: NSDictionary = ["111":"title of the video","123":"title of the other","133":"title of  another"]
if let value = d["123"] {
    print("value for key: 123 is", value)
} else {
    print("there is no value with key 123 in my dictionary")
}
// in case, you have an array of dictionaries
let arr = [["111":"title of the video"],["123":"title of the other"],["133":"title of  another"]]
let values = arr.flatMap { (d) -> String? in
    if let v = d["123"] {
        return v
    } else {
        return nil
    }
}
print(values) // ["title of the other"]

【讨论】:

    猜你喜欢
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    相关资源
    最近更新 更多