Ad

Refactoring And Simplifying For Loops To Be More "Swifty"

- 1 answer

I have a fairly simple for-loop that I would like to refactor to be more "Swifty". I'm sure this is do-able with some kind of map or other cool mechanism. If it's not too much to ask, it would be beneficial of me to hear a thought-process behind refactoring/creating these, as it's one area of Swift that I just can't seem to wrap my head around very well (I'm stuck on an old-school for-loop mindset!).

The loop goes through an array of dictionaries to find the one we need (based on a refKey==refVal), then it simply pulls a different value needed from that particular dictionary based on "keyForWhatWeWant":

for currentDictionary in dictionaries where currentDictionary["refKey"] == "refVal" {
    if let valueWeWant = currentDictionary["keyForWhatWeWant"] {
        return valueWeWant
    }
}

I do want it to pass through this code and move on if it does not find the value, though, FYI.

Ad

Answer

You can use Swift collection method first where predicate to find the dictionaries that fit your criteria and then get its key "keyForWhatWeWant". IMO the for loop approach seems cleaner:

if let valueWeWant = dictionaries.first(where: { 
    $0["refKey"] == "refVal" && $0["keyForWhatWeWant"] != nil 
})?["keyForWhatWeWant"] {
    print("valueWeWant:", valueWeWant)
}
Ad
source: stackoverflow.com
Ad