How to create functions with optional parameters in Swift
What are Parameters
Parameters are what is in-between opening and closing parentheses ex; ‘(parameters go here)’ used to specify values when calling methods.
What are Optional Parameters
The key word here is Optional meaning not required. So these parameters have values that can be set, however you can chose to use the function with no parameters.
As you can see the only difference between a normal function with parameters and a function with optional parameters is that we specify the defaults for each value in our parameters. unlike normal variables function parameters must have their data type specified even if we are assigning a obvious data type such as an integer, or a string. The nice thing about this is that we don’t have to write two functions, one with parameters and one without parameters. This saves us lines of code. The less repetitive our code is the better.
As you can see Xcode’s auto complete feature handles our function properly by giving us the option to select the function with parameters and the other function without parameters. Xcode makes it seem as if it where two function even though its all coming from one function. This blew my mind when I found out about this earlier today. Thanks for reading this article, stay tuned for more content.