Closure question

Hey guys. I've got that closure from swift book

numbers.map({ (number: Int) -> Int in
    let result = 3 * number
    return result
})

how to assign the result of it to some variable after?
Many thanks

1 Like

You assign it before passing in. This is like you pass in a constant, doSomething("woah"). In case of string constant, you can make another copy later:

doSomething("woah")
let value = "woah"

but that'd just be a copy. Instead you want to create a value, and the pass it in:

var value = "woah"
doSomething(value)

Similarly with closure:

let closure = { (number: Int) -> Int in
  let result = 3 * number
  return result
}
numbers.map(closure)

Note that you need to provide enough information so that the type of closure is known where it is declared (let closure). In this case, it's alright because you already specify that it takes 1 argument of type Int, and return a value of type Int.

2 Likes
let results = numbers.map({ (number: Int) -> Int in
    let result = 3 * number
    return result
})
1 Like