ios 在 Swift 中搜索字典数组以获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28203443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:34:37  来源:igfitidea点击:

Search Array of Dictionaries for Value in Swift

iosarraysxcodeswiftdictionary

提问by Adrian

I'm new to Swift and taking a class to learn iOS programming. I find myself stumped on how to search in an array of dictionaries for a string value and dump the string value into an array. This is taken from my Xcode playground.

我是 Swift 的新手,正在上课学习 iOS 编程。我发现自己很难过如何在字典数组中搜索字符串值并将字符串值转储到数组中。这是从我的 Xcode 游乐场中获取的。

I'm trying to figure out how to: 1) search through an array of dictionaries 2) dump the results of the search into an array (which I've created)

我试图弄清楚如何:1) 搜索字典数组 2) 将搜索结果转储到一个数组中(我创建的)

These are the character dictionaries.

这些是字符字典。

let worf = [
    "name": "Worf",
    "rank": "lieutenant",
    "information": "son of Mogh, slayer of Gowron",
    "favorite drink": "prune juice",
    "quote" : "Today is a good day to die."]

let picard = [
    "name": "Jean-Luc Picard",
    "rank": "captain",
    "information": "Captain of the USS Enterprise",
    "favorite drink": "tea, Earl Grey, hot"]

This is an array of the character dictionaries listed above.

这是上面列出的字符字典的数组。

let characters = [worf, picard]

This is the function I'm trying to write.

这是我正在尝试编写的函数。

func favoriteDrinksArrayForCharacters(characters:Array<Dictionary<String, String>>) -> Array<String> {
    // create an array of Strings to dump in favorite drink strings
    var favoriteDrinkArray = [String]()

    for character in characters {
        // look up favorite drink

        // add favorite drink to favoriteDrinkArray
    }

    return favoriteDrinkArray
}

let favoriteDrinks = favoriteDrinksArrayForCharacters(characters)

favoriteDrinks

I would be grateful for any assistance on how to move forward on this. I've dug around for examples, but I'm coming up short finding one that's applicable to what I'm trying to do here.

我将不胜感激任何有关如何推进这一点的帮助。我已经挖掘了一些例子,但我很快就会找到一个适用于我在这里尝试做的事情。

回答by Airspeed Velocity

Inside the loop, you need to fetch the "favorite drink" entry from the dictionary, and append it to the array:

在循环内部,您需要从字典中获取“最喜欢的饮料”条目,并将其附加到数组中:

for character in characters {
    if let drink = character["favorite drink"] {
        favoriteDrinkArray.append(drink)
    }
}

Note, the if let drink =guards against the possibility there is no such entry in the array – if there isn't, you get a nilback, and the ifis checking for that, only adding the entry if it's not nil.

注意,if let drink =防止数组中没有这样的条目的可能性——如果没有,你会得到一个nil返回,并且if正在检查它,如果它不是零,则只添加条目。

You might sometimes see people skip the if letpart and instead just write let drink = character["favorite drink"]!, with an exclamation mark on the end. Do not do this. This is known as "force unwrapping" an optional, and if there is ever not a valid value returned from the dictionary, your program will crash.

有时您可能会看到人们跳过这if let部分,而只是写let drink = character["favorite drink"]!,末尾带有感叹号。 不要这样做。这被称为“强制解包”一个可选项,如果没有从字典返回有效值,您的程序将崩溃。

The behavior with the first example is, if there is no drink you don't add it to the array. But this might not be what you want since you may be expecting a 1-to-1 correspondence between entries in the character array and entries in the drinks array.

第一个示例的行为是,如果没有饮料,则不要将其添加到数组中。但这可能不是您想要的,因为您可能期望字符数组中的条目和饮料数组中的条目之间存在 1 对 1 的对应关系。

If that's the case, and you perhaps want an empty string, you could do this instead:

如果是这种情况,并且您可能想要一个空字符串,则可以这样做:

func favoriteDrinksArrayForCharacters(characters: [[String:String]]) -> [String] {
    return characters.map { character in
        character["favorite drink"] ?? ""
    }
}

The .mapmeans: run through every entry in characters, and put the result of running this expression in a new array (which you then return).

.map方法:通过在每个条目运行characters,并把运行在一个新的数组这个表达式(你然后返回)的结果。

The ??means: if you get back a nilfrom the left-hand side, replace it with the value on the right-hand side.

??手段:如果你得到一个nil从左侧,与在右边的值替换它。

回答by Antonio

Airspeed Velocity's answer is very comprehensive and provides a solution that works. A more compact way of achieving the same result is using the filterand mapmethods of swift arrays:

Airspeed Velocity 的回答非常全面,并提供了一个有效的解决方案。实现相同结果的更紧凑的方法是使用swift 数组的filtermap方法:

func favoriteDrinksArrayForCharacters(characters:Array<Dictionary<String, String>>) -> Array<String> {
    // create an array of Strings to dump in favorite drink strings
    return characters.filter { 
["prune juice", "tea, Earl Grey, hot"]
["favorite drink"] != nil }.map {
let drinks = characters.map({
let drinks = characters.filter({
var customerNameDict = ["firstName":"karthi","LastName":"alagu","MiddleName":"prabhu"];
var clientNameDict = ["firstName":"Selva","LastName":"kumar","MiddleName":"m"];
var employeeNameDict = ["firstName":"karthi","LastName":"prabhu","MiddleName":"kp"];

var attributeValue = "karthi";

var arrNames:Array = [customerNameDict,clientNameDict,employeeNameDict];

var namePredicate = NSPredicate(format: "firstName like %@",attributeValue);

let filteredArray = arrNames.filter { namePredicate.evaluateWithObject(
  Use the following code to search from NSArray of dictionaries whose keys are ID and Name.

      var txtVal:NSString
      let path = NSBundle.mainBundle().pathForResource(plistName, ofType: "plist")
      var list = NSArray(contentsOfFile: path!) as [[String:String]]

      var namePredicate = NSPredicate(format: "ID like %@",  String(forId));
      let filteredArray = list.filter { namePredicate!.evaluateWithObject(
 for  index in self.customerArray
    {
        var string = index.valueForKey("phone")
        if let phoneNumber = index.valueForKey("phone") as? String {
            string = phoneNumber
        }
        else
        {
            string = ""
        }
        if string!.localizedCaseInsensitiveContainsString(searchText) {
            filtered.addObject(index)
            searchActive = true;
        }

    }
) }; if filteredArray.count != 0 { let value = filteredArray[0] as NSDictionary txtVal = value.objectForKey("Name") as String }
) }; println("names = ,\(filteredArray)");
["favorite drink"] != nil}).map({##代码##["favorite drink"]!}) // [prune juice, tea, Earl Grey, hot]
["favorite drink"]}) // [Optional("prune juice"), Optional("tea, Earl Grey, hot")]
["favorite drink"]! } }

The filter takes a closure returning a boolean, which states whether an element must be included or not - in our case, it checks for the existence of an element for key "favorite drink". This method returns the array of dictionaries satisfying that condition.

过滤器接受一个返回一个布尔值的闭包,它说明是否必须包含一个元素 - 在我们的例子中,它检查 key 元素的存在"favorite drink"。此方法返回满足该条件的字典数组。

The second step uses the mapmethod to transform each dictionary into the value corresponding to the "favorite drink" key - taking into account that a dictionary lookup always returns an optional (to account for missing key), and that the filter has already excluded all dictionaries not having a value for that key, it's safe to apply the forced unwrapping operator !to return a non optional string.

第二步使用该map方法将每个字典转换为对应于"favorite drink" 键的值- 考虑到字典查找总是返回一个可选的(以考虑丢失的键),并且过滤器已经排除了所有没有该键的值,应用强制解包运算符!返回非可选字符串是安全的。

The combined result is an array of strings - copied from my playground:

组合结果是一个字符串数组 - 从我的操场复制:

##代码##

回答by Aleksey G.

##代码##

or

或者

##代码##

回答by Sachin Nikumbh

It may help you

它可能会帮助你

##代码##

回答by Himanshu Mahajan

##代码##

回答by Amol Pokale

i have array of customer ,each customer having name,phone number and other stubs .so i used the below code to search by phone number in the array of dictionary in search bar

我有客户数组,每个客户都有姓名、电话号码和其他存根。所以我使用下面的代码在搜索栏中的字典数组中按电话号码搜索

##代码##