Created
March 1, 2017 17:05
-
-
Save saoudrizwan/88b977232f58c0724d1b5b627cb84820 to your computer and use it in GitHub Desktop.
Get a lil functional with your arrays
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
// .filter() returns a new array of elements that satisfy a predicate declared in our closure | |
let evenNumbers = [1, 2, 3, 4, 5].filter { $0 % 2 == 0 } | |
// .map() returns a new array after applying a function to each element | |
let numbers = [1, 2, 3, 4, 5].map { $0 * 2 } | |
print(numbers) // [2, 4, 6, 8, 10] | |
// .flatMap() is like .map(), except it filters out any nil values | |
let arrayWithNoNils = [1, 2, 3, nil].flatMap { $0 } | |
print(arrayWithNoNils) // [1, 2, 3] | |
// .sorted() returns an array sorted according to a given function with a predicate | |
let sortedNumbers = [3, 1, 5, 6, 2, 4].sorted { $1 > $0 } | |
print(sortedNumbers) // [1, 2, 3, 4, 5, 6] | |
// .forEach() calls a given closure to each element (doesn't return a new array) | |
let numbers = [1, 2, 3, 4, 5] | |
numbers.forEach { print($0) } | |
// swipeCells.forEach { $0.hideSwipe(animated: true) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment