Search code examples
swiftfilterfunctional-programmingreducemap-function

How to map over an array, use an if clause, and filter out the bad data?


I have an array of words, some may or may not have typos.

potentialWords = ["hello", "lkasjdf", "hunry"]

What I want to do is, return an array of all valid words, and also those words that were able to be autocorrected using a function I created correctWord. It returns an array of potential matches. so "hunry" might return ["hungry", "hurry"]. I will select the first index for the best guess.

Some words cannot be corrected however! e.g. "lkasjdf" will not find any corrections, but "hunry" will.

I was trying something like:

potentialWords.map {
  if correctWord($0) != nil {
    return correctWord($0)[0]
  } 
}

of course this will complain and say that I need a return outside the if clause. I can filter the list based on if the word can be corrected, and then map over the filtered list, re-checking which words need to be corrected, but this runs the correctWord function way too many times, and it is very sensitive.

I would like to be able to do one single pass through, and return an array of all valid words, and also corrected words.

P.S. I am calling correctWord twice in the map function for brevity, but of course I would assign correctWord($0) to a variable, and then if it isn't nil, take the first index and add it to the new list.


Solution

  • I think you're after flatMap. It's the same as map except it will also filter out any nil values.

    potentialWords.flatMap { correctWord($0)?.first }