Tuesday, April 5, 2016

When to use map, flatMap, or for loops in Swift

Use map when you need to transform arrays

let arrayOfNumbers = [1, 2, 3, 4]
let arrayOfString = arrayOfNumbers.map { "\($0)" }

In the context of Array map get an array, applies a transformation function to every element, and returns a new array with the resulting elements. . That's the best use case for map.

Use for loops when there are "side effects"

Without going into details an operation has a side effect if it results in some kind of state changing somewhere, for example changing the value of a variable, writing to disk, or updating the UI. In such case using a for loop is more appropriate.

for number in arrayOfNumbers {
  print(number)
}

And what about flatMap?

When you need to transform the contents of an array of arrays, into a linear array use flatMap:

let users: [User] = ...
let allEmails = users.flatMap { $0.emails }

p/s: No difference about performance.

Thanks to this

No comments:

Post a Comment