Functions are central in Swift. We’ll learn about functions with a few different examples.
To run this Swift code, you would typically save it in a file with a .swift extension, for example functions.swift, and then use the Swift compiler or Swift REPL:
There are several other features to Swift functions. One is multiple return values, which we’ll look at next.
Swift has some key differences from other languages when it comes to functions:
Swift uses the func keyword to declare functions.
Parameter names are part of the function’s signature and are used when calling the function, unless you use an underscore _ to allow calling without an external name.
The return type is specified after the -> symbol.
Swift supports implicit returns for single-expression functions, though we’ve used explicit returns here for clarity.
Swift doesn’t require a main() function as an entry point. Code at the top level of a file is executed when the program starts.
These examples demonstrate basic function syntax and usage in Swift, showing how to define functions with different parameters and return values, and how to call these functions.