[Swift] How do I create and call a function in Swift?

To create and call a function in Swift, you can follow these steps:

  1. Declare the function: Start by writing the keyword func, followed by the function name. Include parentheses () after the function name to indicate that it is a function.
1func functionName() {
2    // Function body
3}
  1. Add parameters (if necessary): Inside the parentheses, you can specify any parameters that the function may require. Parameters are defined by providing a name followed by its type.
1func functionName(parameter1: Int, parameter2: String) {
2    // Function body
3}
  1. Define the function body: Write the code that will be executed when the function is called within the curly braces {}.
1func functionName(parameter1: Int, parameter2: String) {
2    // Function body
3    // Code to be executed
4}
  1. Call the function: To execute the function and invoke its code, simply write the function name followed by parentheses ().
1functionName(parameter1: 10, parameter2: "Hello")

Note: Make sure to provide the correct values and data types for the parameters according to the function's definition.

Here's an example that demonstrates creating and calling a function in Swift:

1func greet(name: String) {
2    print("Hello, \(name)!")
3}
4
5greet(name: "John")

Output:

1Hello, John!

In this example, we define a function called greet that takes a name parameter of type String. When we call the function with the argument "John", it prints out "Hello, John!".