First-class functions in Swift

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

First-class functions are the core feature of a functional programming language. Swift isn’t a functional programming language. But, it has the power of first-class functions. In this short article let’s have a look at the first-class functions and their application.

What can we achieve through first-class functions?

Functions are first-class citizens in Swift. Grasping this powerful concept will make developer life easier. Swift first-class functions have the following abilities –

  • You can store functions in constants and variables.
  • You can pass a function or functions as arguments to other functions.
  • One can also return functions from other functions.

Storing functions in variables

We can store a function in a variable or constant. For instance, create a property named feed. The feed property has a function type that is optional. This type does not accept any arguments and returns nothing.


The entertain() function uses feed property references to do the specific feed action.

final class CatManager {
    var feed: (() -> Void)?

    func entertain() {
        feed?()
        // ... other important code that makes cat happy
    }
}

// Here, we store the function in a variable
// and uses it later inside another function


func feedAction() -> Void {
  // Code for providing delicious cat food,
  // Water and milk
}

// Add the functionality in feed
let catManager = CatManager()
catManager.feed = feedAction

// Can be done using closure
catManager.feed = {
  // Code for providing delicious cat food,
  // Water and milk
}


// Output will be ...
// Code for providing delicious cat food,
// Water and milk
// ... other important code that makes cat happy

Passing the functions as arguments

Above all, Passing functions as arguments are using all most everywhere in Swift. SwiftUI is mostly based on this concept. You can read Map, FlatMap, Filter, Reduce – High order functions in Swift 5.4 to understand passing function as an argument and the use of closure.

Let’s create a function named greetings() and pass it process(action...) function. Here, passing a function as an argument makes the code readable and manageable. To make the function passing more manageable, you can use typealias which is described here – How and when to use typealias in Swift?

func greetings() -> Void {
    print("Good Morning!")
}

func process(_ action: () -> Void) {
    action()
    print("Start the day with a big smile 😁")
}

process(action: greetings)

// Output 
// Good Morning!
// Start the day with a big smile 😁

Returning function from a function

Return of functions from functions causes the greatest difficulties for beginners. Returning function is not complicated in itself. But, it is difficult to understand why this may be necessary. This technique is often used in real life, both in Swift and in many other functional programming languages. In the code example, I have created an ActionType enum and passed it to processNumbers function. Based on the actionType, the function returns((_ items: Int…) -> Int) different action. I am using variadic parameters in the add, multiply and specialAdd functions. (More about the variadic parameter is described here – How to use Variadic Parameters in Swift 5.4?)

enum ActionType {
    case add
    case multiply
    case specialAdd
}

func processNumbers(by actionType: ActionType) -> (_ items: Int...) -> Int {

    func add(_ numbers: Int...) -> Int {
        return numbers.reduce(0, +)
    }

    func multiply(_ numbers: Int...) -> Int {
        return numbers.reduce(0, *)
    }

    func specialAdd(_ numbers: Int...) -> Int {
        return numbers.reduce(0) { (result, number) -> Int in
            return result + number * 2
        }
    }

    switch actionType {
    case .add:
        return add
    case .multiply:
        return multiply
    default:
        return specialAdd
    }
}

let process = processNumbers(by: .add)
process(1, 2, 3, 4)

// Output
// 10

Planning to apply for an iOS job? Check out this article to uplift your resume! Also helpful – SwiftUI and Swift Interview preparation. Happy job hunting!



✍️ Written by Ishtiak Ahmed

πŸ‘‰ Follow me on X ● LinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.