Created
June 19, 2018 14:11
-
-
Save lamprosg/7cc1f17eb601564a58442eb7c597eebc to your computer and use it in GitHub Desktop.
(iOS) Collection higher order functions
This file contains hidden or 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
| //Map | |
| //Loops over a collection and applies the same operation to each element in the collection. | |
| var numberArray = [1,2,3,4,5] | |
| var newArray = numberArray.map( {(value:Int) -> Int in | |
| return value*2 | |
| }) | |
| //or quicker | |
| var newArray = numberArray.map{$0*2} | |
| //newArray = [2,4,6,8,10] |
This file contains hidden or 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 | |
| //Loops over a collection and returns an array that contains elements that meet a condition. | |
| let numbersArray = [1,2,3,4,5,6,7,8,9,10,11,14,15] | |
| //filter them | |
| let evenArray = numbersArray.filter{$0 % 2 == 0} |
This file contains hidden or 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
| //Reduce | |
| //Combines all items in a collection to create a single value. | |
| var oneTwoFive = [1,2,3,4,5] | |
| //Reduce | |
| //The addition of two adjacent values is taking place between the {} brackets, and the sum is then added to the 0 on the left. | |
| var sum = oneTwoFive.reduce(0, {$0 + $1}) | |
| //sum = 15 | |
| //Easier way | |
| //the + operator is substituted for the {$0 + $1} closure, creating an even more simplified and accessible syntax | |
| var sum = oneTwoFive.reduce(0, +) |
This file contains hidden or 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
| //Flatmap | |
| //When implemented on sequences : Flattens a collection of collections. | |
| let arrayInArray = [[11,12,13],[14,15,16]] | |
| let flattenedArray = arrayInArray.flatMap{$0} | |
| //flattenedArray = [11,12,13,14,15,16] | |
| //Removing nils from a collection | |
| let people:[String?] = ["Joyce",nil,"rob",nil,"Maria"] | |
| let validPeople = people.flatMap{$0} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment