Functions in Swift

The following is the syntax to declare a function.

Functions are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed. Functions can also be written within other functions to encapsulate useful functionality within a nested function scope.

Simple Function Example:

Every function has a function name, which describes the task that the function performs. To use a function, you “call” that function with its name and pass it input values (known as arguments) that match the types of the function’s parameters. A function’s arguments must always be provided in the same order as the function’s parameter list.

The function in the example above is called sayHello, because that’s what it does—it takes a person’s name as input and returns a greeting for that person. To accomplish this, you define one input parameter—a Stringvalue called personName—and a return type of String, which will contain a greeting for that person. All of this information is rolled up into the function’s definition, which is prefixed with the func keyword. You indicate the function’s return type with the return arrow -> (a hyphen followed by a right angle bracket), which is followed by the name of the type to return.

Function Call:

The definition describes what the function does, what it expects to receive, and what it returns when it is done. The definition makes it easy for the function to be called unambiguously from elsewhere in your code:

The body of the sayHello function starts by defining a new String constant called greeting and setting it to a simple greeting message for personName. This greeting is then passed back out of the function using thereturn keyword. As soon as return greeting is called, the function finishes its execution and returns the current value of greeting.

Function Parameters and Return Values:

Functions Without Parameters

Functions are not required to define input parameters. Here’s a function with no input parameters, which always returns the same String message whenever it is called:

the function definition still needs parentheses after the function’s name, even though it does not take any parameters. The function name is also followed by an empty pair of parentheses when the function is called.

Functions Without Return Values

Functions are not required to define a return type. Here’s a version of the sayHello function, calledsayGoodbye, which prints its own String value rather than returning it:

Because it does not need to return a value, the function’s definition does not include the return arrow (->) or a return type.

  • Functions without a defined return type return a special value of type ‘Void'.
  • This is simply an empty tuple, in effect a tuple with zero elements, which can be written as ()
  • Return values can be ignored, but a function that says it will return a value must always do so.
  • A function with a defined return type cannot allow control to fall out of the bottom of the function without returning a value, and attempting to do so will result in a compile-time error.

Functions with Multiple Return Values

You can use a tuple type as the return type for a function to return multiple values as part of one compound return value.

The example above defines a function called minMax, which finds the smallest and largest numbers in an array of Int values:

  • The minMax function returns a tuple containing two Int values (min , max). These values are labeled min and max so that they can be accessed by name when querying the function’s return value.
  • The body of the minMax function starts by setting two working variables called currentMin and currentMax to the value of the first integer in the array.
  • The function then iterates over the remaining values in the array and checks each value to see if it is smaller or larger than the values of currentMin and currentMax respectively.
  • Finally, the overall minimum and maximum values are returned as a tuple of two Int values.
  • The function call is assigned to a constant ‘bounds’.
  • minMax will iterate thought the array an will return a tuple.
  • The tuple min will bare the currentMin value and the max will bare the currentMax value.
  • Constant bounds is inferred as tuple implicitly.
  • Thus the string place holder \() calls the value as bound.min & bound.max.

Optional Tuple as a Return Type

If the array argument, as defined above, contains an empty array—that is, an array with a count of 0—the minMax function will trigger a runtime error when attempting to access array[0]. In such cases we use Optional Tuple as a return type. 

If the tuple type to be returned from a function has the potential to have “no value” for the entire tuple, you can use an optional tuple return type to reflect the fact that the entire tuple can be nil.You write an optional tuple return type by placing a question mark after the tuple type’s closing parenthesis, such as (Int, Int)? or(String, Int, Bool)?

  •  An optional tuple type such as (Int, Int)? is different from a tuple that contains optional types such as(Int?, Int?).
  • With an optional tuple type, the entire tuple is optional, not just each individual value within the tuple.

Next we will learn about function’s parameter name and its different thumb rules.