The Anatomy of a Swift Function
Functions are self-contained chunks of code that perform a specific task. In Swift, functions are first-class citizens, meaning they can be passed as arguments, returned from other functions, and assigned to variables. As a Technical Lead, you'll appreciate how Swift forces a clear contract between the caller and the implementation through its unique parameter naming system.
- Argument Labels and Parameter Names
Swift distinguishes between the argument label (used when calling the function) and the parameter name (used within the function body). This allows the function call to be expressive while keeping the internal logic concise.
- Returning Values and Tuples
Functions use the -> symbol to indicate return types. A powerful feature for architects is the ability to return Tuples, allowing a function to return multiple values without needing to define a custom struct or class.
- Default and Variadic Parameters
Swift supports default parameter values, reducing the need for function overloading. It also supports Variadic Parameters, which allow a function to accept zero or more values of a specified type, accessible as an array within the function.
Function Feature Comparison
| Feature | Swift | Dart (Flutter) |
|---|---|---|
| Declaration | func keyword | Type-first or void |
| Return Symbol | -> | Implicit by position |
| Multiple Returns | Tuples (Native) | Records (Dart 3.0+) |
| Argument Labels | External/Internal labels | Named parameters { } |
| Omit Label | Use underscore (_) | Optional by default |