Home > Enterprise >  Refactoring and simplifying for loops to be more "Swifty"
Refactoring and simplifying for loops to be more "Swifty"

Time:02-13

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.

CodePudding user response:

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)
}
  • Related