Functions as First-Class Citizens

I. What Are “First-Class Citizens”?

First-Class Citizens refer to entities (typically data types) in a programming language that can be used like variables.

They must satisfy three key characteristics:

Characteristic Meaning
Assignable Can be assigned to variables or constants
Passable as parameters Can be passed as arguments to other functions
Returnable Can be returned from other functions

In Swift, functions are first-class citizens!


II. Demonstrating Functions’ First-Class Capabilities in Swift

1. Functions can be assigned to variables/constants

1
2
3
4
5
6
func getCourseName() -> String {
return "App Design: UI, UX and Development"
}

let course = getCourseName // No parentheses: assigning the FUNCTION ITSELF
print(course()) // Calling the function: prints the string

💡 Key distinction:
getCourseName refers to the function body,
getCourseName() calls the function and returns its result.


2. Functions can be passed as parameters

1
2
3
4
5
6
7
8
9
func getCourseName() -> String {
return "App Design"
}

func showCourse(nameProvider: () -> String) {
print(nameProvider()) // Calls the provided function
}

showCourse(nameProvider: getCourseName) // Passing function as argument

💡 Parameter nameProvider has type () -> String (a function taking no arguments and returning String).


3. Functions can be returned from other functions

1
2
3
4
5
6
7
8
9
10
func getCourseName() -> String {
return "Swift Development"
}

func getFunction() -> () -> String {
return getCourseName
}

let result = getFunction()() // First () calls getFunction, second calls returned function
print(result)

💡 () -> String denotes “a function returning String”.


IV. Advanced Usage: Storing Functions in Data Structures

Functions can be stored in collections like arrays, dictionaries, or sets.

1
2
3
4
5
6
let getCourseName = { return "Swift" }
let courses: [() -> String] = [getCourseName, getCourseName, getCourseName]

for course in courses {
print(course())
}

V. Significance & Applications

Scenario Applications
Closures Swift closures are anonymous functions
Higher-order functions (map/filter/reduce) All take functions as parameters
Functional Programming Enables flexible, composable code structures
Asynchronous callbacks Completion handlers rely on passing functions
UI Programming .addTarget passes functions as action handlers

Summary

In Swift, functions aren’t just callable—they can be passed, returned, and stored with the same flexibility as variables. This unlocks powerful programming paradigms.