Swift Transforming Arrays

Swift Transforming Arrays

——by《Advanced Swift》

In Swift, Array object has a number of Transforming methods, there are map, filter, reduce, flatMap, etc.

Map

Every programmer has writtern similar code hundreds of times: create a new array, loop over all elements in an existing array, perform an operation on an element, and append the result of that operation to the new array. For example, the follwing code squares an array of integers:

1
2
3
4
5
let fibs = [1, 2, 3, 4]
var sauared: [Int] = []
for fib in fibs {
sauared.append(fib * fib)
}

Swift arrays have a map method, adopted from the world of functional programming. This method can perform a transformation on every value in the array. So, the above code can write like this:

1
let sauared = fibs.map { fib in fib * fib }

Use map method has three main advantages:

  • It’s shorter, and more importantly, it’s clearer. The map acts a signal, you know immediately what is happening when you see it: a function is going to be applied to every element, returning a new array of the transformed elements.
  • We can declare squared with let, because we aren’t mutating it any longer when use map method.
  • map isn’t hard to write – it’s just need to wrapping up the boilerplate parts of the for loop into a generic function. Here’s one possible implementaion:
1
2
3
4
5
6
7
8
9
10
extension Array {
func my_map<U>(transform: Element -> U) -> [U] {
var result: [U] = []
result.reserveCapacity(self.count)
for x in self {
result.append(transform(x))
}
return result
}
}

Parameterizing Behavior with Functions

map manages to separate out the boilerplate functionality – which doesn’t vary from call to call – from the funcionality that always varies: the logic of how exactly to fransform each element.
This pattern of parameterizing behavior is found throughout the standard library. There are 13 separate functions that take a closure that allows the caller to customize the key step:

  • map and flatMap – how to tranform an element
  • filter – should an element be included?
  • reduce – how fo fold an element into an aggregate value
  • sort and lexicographicCompare – in what order should two elements come?
  • indexOf and contains – does this elements match
  • minElement and maxElement – which is the min/max of two elements?
  • elementsEqual and startsWith – are two elements equivalent?
  • split – is this element a separator?
坚持原创技术分享,您的支持将鼓励我继续创作!