Search code examples
iosswiftclosuresidentifier

Identifier error with closures? | Swift Tour - Closures


So in the "Swift Tour" (https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html) is a part about closures.
The code in their example is the following:

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

But when tryin to run this, you get following error: " error: use of unresolved identifier 'numbers' "

So my questions are:

  1. What are closures/ Could anyone explain the usage of these?
  2. What is wrong with the example (it´s the official code example of the Swift documentation..)

Solution

  • The array numbers is declared on line 12 of the previous code block. Each code block shown in that chapter builds on the one before. You can download the code as a playground

    The functioning code block would be:

    var numbers = [20, 19, 7, 12]
    
    numbers.map({ (number: Int) -> Int in
        let result = 3 * number
        return result
    })
    

    Closures are described in more detail in their own chapter but in summary:

    Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

    In the case of the map function, the code in the closure operates on each element of the array in turn. It accepts the array element as input and returns an element for the output array.

    You can return 0 for odd numbers using the modulo function

    let evens = numbers.map({ (number: Int) -> Int in
        if number % 2 == 0 {
            return number
        } else {
            return 0
        }
    })