- Mastering macOS Programming
- Stuart Grimshaw
- 162字
- 2021-07-02 22:54:32
First class functions
You have probably heard this before, but here it is again anyway: Swift functions are first class entities. This is not some commentary about the quality of the functions we write (unfortunately); rather it means that functions are objects themselves and like any other object can be passed as arguments to other functions.
It also means that functions can return other functions.
Functions that either take other functions as an argument, or have a function return value type are called higher order functions.
This is a big thing in Swift. Whereas in Objective C, passing code blocks was bolted on as an afterthought (and not very elegantly at that), first class functions are central to the Swift language, forming an essential part of its standard library, as well as being one of its more powerful, future-orientated features.
Many functions in Swift take a function as an argument, usually in the form of a closure, as we shall see shortly.