Skip to content

Instantly share code, notes, and snippets.

@josh-marasigan
Last active April 28, 2018 15:22
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 josh-marasigan/434555503e484a68befcf1f739b04691 to your computer and use it in GitHub Desktop.
Save josh-marasigan/434555503e484a68befcf1f739b04691 to your computer and use it in GitHub Desktop.
Varying Swift syntax for map function
// Most verbose: No compiler assumptions are made, the closure to map
// receives a transforming function explicitly casted as (val: Int) -> Int
// Transforms an array of Int and multiplies each value by 10
arrValues.map({ (val: Int) -> Int in
return val * 10
})
// Compiler assumes return type for closure, no need to explicitly indicate
arrValues.map({ (val: Int) in
return val * 10
})
// Compiler assumes data type for closure parameter (of type Int)
arrValues.map({ (val) in
return val * 10
})
// Compiler assumes last value in closure is returned and is of type Int
arrValues.map({ (val) in
val * 10
})
// Compiler assumes the first (and only, for this case) parameter in closure
// is of type Int, the last value in closure is returned and is of type Int,
// and assumes the return type of the clusre is also of type Int (from the data
// type of the value operated by `$0 * 10` (Int)
arrValues.map({ $0 * 10 })
// Assumes same as above but since the last parameter for map is a closure
// (ie. a trailing closure), there is no need to indicate parenthesis and
// brackets will suffice
arrValues.map{ $0 * 10 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment