Search Array of Dictionaries for Value in Swift

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.

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)

  • Iterating Through a Dictionary in Swift
  • How do you sort an array of structs in swift
  • How to sort array based on another arrays position?
  • How to slice an NSArray in Objective-C?
  • Iterate Dictionary with dictionary data and add it to an array in swift
  • access to array object
  • 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.

    6 Solutions Collect From Internet About “Search Array of Dictionaries for Value in Swift”

    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.

    You might sometimes see people skip the if let part 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.

    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.

    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).

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

    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 filter and map methods of swift arrays:

    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". 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 ! 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")]
    

    or

    let drinks = characters.filter({$0["favorite drink"] != nil}).map({$0["favorite drink"]!}) // [prune juice, tea, Earl Grey, hot]
    
      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
          }
    

    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)");
    

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