简体   繁体   English

在Swift中搜索字典数组的值

[英]Search Array of Dictionaries for Value in Swift

I'm new to Swift and taking a class to learn iOS programming. 我是Swift的新手,上课学习iOS编程。 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. 这是从我的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. 我已经挖掘了一些例子,但我很快找到一个适用于我在这里尝试做的事情。

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 nil back, and the if is checking for that, only adding the entry if it's not nil. 注意, if let drink =防止数组中没有这样的条目的可能性 - 如果没有,你会得到一个nil ,而if正在检查它,只是添加条目,如果它不是nil。

You might sometimes see people skip the if let part and instead just write let drink = character["favorite drink"]! 你有时可能会看到人们跳过if let part而只是写下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. 这被称为“强制解包”一个可选项,如果没有从字典返回的有效值,则程序将崩溃。

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. 但这可能不是您想要的,因为您可能期望字符数组中的条目与drink数组中的条目之间存在一对一的对应关系。

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 .map means: 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 nil from the left-hand side, replace it with the value on the right-hand side. 意思是:如果你从左侧拿回一个nil ,用右边的值替换它。

Airspeed Velocity's answer is very comprehensive and provides a solution that works. Airspeed Velocity的答案非常全面,并提供了有效的解决方案。 A more compact way of achieving the same result is using the filter and map methods of swift arrays: 实现相同结果的更紧凑的方法是使用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 { $0["favorite drink"] != nil }.map { $0["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" . 过滤器接受一个返回一个布尔值的闭包,它指出是否必须包含一个元素 - 在我们的例子中,它检查是否存在关键"favorite drink"的元素。 This method returns the array of dictionaries satisfying that condition. 此方法返回满足该条件的字典数组。

The second step uses the map method 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 ! 第二步使用map方法将每个字典转换为与"favorite drink ”键对应的值 - 考虑到字典查找总是返回一个可选的(以记录丢失的键),并且过滤器已经排除了所有字典没有该键的值,应用强制解包操作符是安全的! to return a non optional string. 返回一个非可选字符串。

The combined result is an array of strings - copied from my playground: 合并后的结果是一个字符串数组 - 从我的操场上复制:

["prune juice", "tea, Earl Grey, hot"]
let drinks = characters.map({$0["favorite drink"]}) // [Optional("prune juice"), Optional("tea, Earl Grey, hot")]

要么

let drinks = characters.filter({$0["favorite drink"] != nil}).map({$0["favorite drink"]!}) // [prune juice, tea, Earl Grey, hot]

It may help you 它可能会帮助你

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($0) };
println("names = ,\(filteredArray)");
  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($0) };
      if filteredArray.count != 0
      {
          let value = filteredArray[0] as NSDictionary
          txtVal = value.objectForKey("Name") as String
      }

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 我有一系列的客户,每个客户都有姓名,电话号码和其他存根。所以我使用下面的代码搜索搜索栏中的字典数组中的电话号码

 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;
        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM