Menu
Coddy logo textTech

Closure Basics

Part of the Logic & Flow section of Coddy's Swift journey — lesson 38 of 56.

A closure is a self-contained block of code you can pass around and call later. The full syntax spells out parameter and return types:

let double = { (n: Int) -> Int in
    return n * 2
}
print(double(5))                  // 10

Swift can infer the types when the context is clear, so you rarely write the long form. Inside map, filter, etc., the shorter shorthand is the norm:

let nums = [1, 2, 3, 4]
let doubled = nums.map { n in n * 2 }
let alsoDoubled = nums.map { $0 * 2 }    // shortest, $0 is the first arg

Closures are values, you can store them in variables, return them from functions, and pass them as arguments. That's the whole reason map works.

challenge icon

Challenge

Easy

Read two lines of input:

  1. An integer x
  2. A comma-separated list of integers

Define three closures, each (Int) -> Int:

  • addX adds x to its argument
  • square returns the argument squared
  • negate returns the argument negated

Apply each closure to every element of the list using map. Print three lines, one per closure, with the results joined by ,:

addX: ...
square: ...
negate: ...

For input 10 on line 1 and 1,2,3 on line 2, the output is:

addX: 11,12,13
square: 1,4,9
negate: -1,-2,-3

Cheat sheet

A closure is a self-contained block of code that can be stored and passed around. Full syntax:

let double = { (n: Int) -> Int in
    return n * 2
}

Closures can be stored in variables and passed as arguments (e.g. to map). Swift infers types in context, enabling shorthand:

let nums = [1, 2, 3, 4]
let doubled = nums.map { n in n * 2 }
let alsoDoubled = nums.map { $0 * 2 }  // $0 is the first argument

Try it yourself

let x = Int(readLine()!)!
let nums = readLine()!.components(separatedBy: ",").map { Int($0)! }

// TODO: define three (Int) -> Int closures and map nums through each
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow