Skip to content

Instantly share code, notes, and snippets.

@saoudrizwan
Created March 1, 2017 17:05
Show Gist options
  • Save saoudrizwan/88b977232f58c0724d1b5b627cb84820 to your computer and use it in GitHub Desktop.
Save saoudrizwan/88b977232f58c0724d1b5b627cb84820 to your computer and use it in GitHub Desktop.
Get a lil functional with your arrays
// .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