Created
March 1, 2016 11:03
-
-
Save miguelfermin/e01a3f50f73fff2a9e2d to your computer and use it in GitHub Desktop.
Swift Functional Programming: Map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Swift Functional Programming: Map | |
// | |
// By Miguel Fermin on 2016.01.28 | |
// | |
// Reference: https://www.weheartswift.com/higher-order-functions-map-filter-reduce-and-more/ | |
import UIKit | |
// The map method solves the problem of transforming the elements of an array using a function. | |
// | |
// It transforms [ x1, x2, ... , xn].map(f) to [f(x1), f(x2), ... , f(xn)] | |
// Task: Convert an array of Ints into an array of Strings with each number appended by a dollar sign '$' | |
let nums = [20, 40, 60, 80, 100] | |
// The old way | |
var result0 = [String]() | |
for num in nums { | |
result0.append("$\(num)") | |
} | |
result0 | |
// Using Array's map method. | |
let result1 = nums.map {"$\($0)"} | |
// result1 equals ["$20", "$40", "$60", "$80", "$100"] | |
// In Swift map is declared as a method on the Array class with signature: | |
// | |
// func map<U>(transform: (T) -> U) -> U[] | |
// | |
// That just means that it receives a function named transform that maps the array element | |
// type T to a new type U and returns an array of U |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment