Functions as First-Class Citizens
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 | func getCourseName() -> 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 | func getCourseName() -> String { |
💡 Parameter nameProvider
has type () -> String
(a function taking no arguments and returning String).
3. Functions can be returned from other functions
1 | func getCourseName() -> String { |
💡 () -> 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 | let getCourseName = { return "Swift" } |
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.
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.