Menu
Coddy logo textTech

Filter

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

filter takes a predicate closure and returns a new array containing only the elements for which the closure returned true.

let nums = [1, 2, 3, 4, 5, 6]
let evens = nums.filter { $0 % 2 == 0 }
print(evens)                 // [2, 4, 6]

The result keeps the original order. The result type matches the input type, no transformation happens, only a selection.

filter chains naturally with map:

let big = nums
    .filter { $0 > 2 }
    .map { $0 * $0 }
print(big)                   // [9, 16, 25, 36]

Read each chain top to bottom, just like a pipeline. Each step produces a new array; nothing modifies the original.

challenge icon

Challenge

Easy

Read two lines of input:

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

Print, on separate lines:

  1. The integers strictly greater than min, joined with , (or empty if none qualify)
  2. The squares of the qualifying integers, joined with ,
  3. The count of qualifying integers

Use filter + map as a chain. Don't iterate twice over the input.

For input 1,5,2,8,3,7 on line 1 and 4 on line 2, the output is:

5,8,7
25,64,49
3

Cheat sheet

Use filter to select elements matching a condition:

let evens = [1,2,3,4].filter { $0 % 2 == 0 } // [2, 4]

Chain filter with map as a pipeline:

let result = nums
    .filter { $0 > 2 }
    .map { $0 * $0 }  // [9, 16, 25, 36]

Each step returns a new array; the original is unchanged. Order is preserved.

Try it yourself

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

// TODO: filter > min once, then map to squares; print both, then count
quiz iconTest yourself

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

All lessons in Logic & Flow