Skip to content

Instantly share code, notes, and snippets.

@Ceri-anne
Created January 7, 2018 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ceri-anne/33417a24b72a8305571c972a6a378c30 to your computer and use it in GitHub Desktop.
Save Ceri-anne/33417a24b72a8305571c972a6a378c30 to your computer and use it in GitHub Desktop.
Playing with Map and FlatMap
// map function
let array = [1,2,3,4,5]
let doubleArray = array.map { $0 * 2 } //produces [2,4,6,8,10]
let players = ["Gerrard", "Dalglish", "Barnes"]
//Create a function upper which takes a String and returns an uppercased String
func upper(name: String) -> String {
return name.uppercased()
}
// Pass this function into the map function
players.map(upper) //produces ["GERRARD", "DALGLISH", "BARNES"]
// Can pass it in as a closure expression (Note: The start of the closure’s body is introduced by the in keyword) This keyword indicates that the definition of the closure’s parameters and return type has finished, and the body of the closure is about to begin.
players.map({
(name: String) -> String in return name.uppercased()
}) //produces ["GERRARD", "DALGLISH", "BARNES"]
// as the closure is the last argment we can remove the ( brackets
players.map {
(name: String) -> String in return name.uppercased()
} //produces ["GERRARD", "DALGLISH", "BARNES"]
//It is always possible to infer the parameter types and return type when passing a closure to a function or method as an inline closure expression.
//Can replace (name: String) -> String with name as Swift knows it is taking a String and producing a String
players.map { name in name.uppercased() } //produces ["GERRARD", "DALGLISH", "BARNES"]
//Swift provides shorthand arguments so we can replace name with $0
players.map { $0.uppercased() } //produces ["GERRARD", "DALGLISH", "BARNES"]
//FlatMap
let liverpoolLegends = players
let liverpoolPlayers = ["Rush", "Fowler", "Owen"]
let liverpool = [liverpoolLegends, liverpoolPlayers] //produces [["Gerrard", "Dalglish", "Barnes"], ["Rush", "Fowler", "Owen"]]
liverpool.flatMap { $0 }) //produces ["Gerrard", "Dalglish", "Barnes", "Rush", "Fowler", "Owen"]
//liverpool.flatMap{ $0.uppercased() }
//ERROR
//Value of type '[String?]' has no member 'uppercased'
//$0 is each array, not the values of the array, so we need to map
liverpool.flatMap{ $0.map{ $0.uppercased() } } //produces ["GERRARD", "DALGLISH", "BARNES", "RUSH", "FOWLER", "OWEN"]
// Also used to "magically" remove optional values
let strings = ["Hello", "World", nil, "Goodbye", nil]
strings.flatMap { $0 } //produces ["Hello", "World", "Goodbye"]
strings.flatMap { $0?.uppercased() } //produces ["HELLO", "WORLD", "GOODBYE"]
//need to use the ? as $0 is optional
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment