← Back to notes
TECHNICAL FIELD NOTES

Higher order functions in Swift 3#2

Examples of filter and reduce in Swift 3 for selecting students and combining their ages into a single value.

Previously published at Original on the previous platform ↗ · First published

Archive note (2026-10-18): This article preserves Swift 3-era examples and APIs, not current setup advice. The examples depend on the Student definition in part 1. Code has only been reformatted and typographic quotes normalized; samples were not executed.

ภาพประกอบ

http://streetwill.co/posts/624-a-day-in-sf

In the first part we’ve learned about simple higher-order function and map function in Swift.

And today we will talk about filter and reduce that are higher-order functions build-in Swift.

Filter is…

Function that given an element in the array and return only match condition elements to result array.

ภาพประกอบ

Filter return Bool indicating whether the element should be include in the result.

// Sample Data
let anak = Student(name: "Anak", age: 30)
let peter = Student(name: "Peter", age: 31)
let steven = Student(name: "Steven", age: 25)
let susan = Student(name: "Susan", age: 20)
let ethan = Student(name: "Ethan", age: 28)

let students = [anak, peter, steven, susan, ethan]

// func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]
// short-hand syntax
let studentsAgeUnder30 = students.filter({ $0.age < 30 })
// Result : [steven, susan, ethan]

// long form syntax
let studentsNameHasAPrefix = students.filter { (student) -> Bool in
    return student.name.lowercased().hasPrefix("a")
}
// Result : [anak]

In the example we want to list all students has age under 30 to new array. We just use filter function with custom condition age < 30 in closure. Also we can use filter in more declarative way.

Reduce is…

Function that reduces an array to a single value.

Reduce take two parameters… first is a starting value and the second is a function. Reduce function takes a running total and returns a value that is created by combining the item in an array.

But have something difference map, filter because those function return the same type but reduce changes the type.

Let’s consider the following example:

// func reduce<U>(initial: U, combine: (U, T) -> U) -> U
// short-hand syntax
let total = students.reduce(0, { $0 + $1.age })

// long form syntax
let totalOfStudentAge = students.reduce(0) { (total, student) -> Int in
    return total + student.age
}
// total : 134

An example we just sum of student age in student list array. We can get sum of age in one line, don’t need to create for-loop and make our code look clean and readable.

ภาพประกอบ

FINALLY!

Hopefully, This article will make you understand what is and how to use higher-order function, map, filter, reduce

Finally, you can leave your comment below. Let’s share idea! Bye bye ❤

Read more notes →