Learn Swift: A whirlwind tour of the Swift programming language by Finn Aidan

Learn Swift: A whirlwind tour of the Swift programming language by Finn Aidan

Author:Finn, Aidan [Finn, Aidan]
Language: eng
Format: mobi
Published: 2015-06-03T16:00:00+00:00

11.2.1 Closure expressions

Closures are defined using curly brackets and the in keyword. The syntax for a closure is

{ (params) -> return_type in statements }

Lets take a look at an example. One common idiom in functional programming is to transform a sequence by applying a closure to each element using map. Swift’s Array type has such a map function which takes a closure and applies it to each element in the sequence.

We’ll start by just using a standard functions (remember closures are anonymous functions, often used for convenience where there’s no need to define a fully fledged function.).

Let’s say we have an array of numbers and we want to double each number in the array. We can use map and pass it a function that will double the number that is passed as an argument.

let nums = [1, 3, 5, 7] func doubler(x:Int) -> Int{ return(x * 2) } let fnDoubledNums = nums.map(doubler) // [2, 6, 10, 14]



Loading...
Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Web Analytics