Mastering in Swift Functions

Types of Swift Functions

Sridharan T
IVYMobility TechBytes
3 min readApr 1, 2020

--

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:

Functions With Parameters

Functions can have multiple input parameters, which are written within the function’s parentheses, separated by commas.

In the above code, greet(user: “Isac”) calls the function and passes value Isac of type String. After that, the print statement inside the function executes.

Function Without Return Values

Functions are not required to define a return type. Here’s a version of the greet(user: ) function, 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.

Function With Return Values

The return keyword tells the program to leave the function and return to line where the function call was made.

You can also pass a value with the return keyword where value is a variable or other information coming back from the function.

In the above code, greet(user: “Isac”) calls the function and passes value Isac of type String. return “Good Morning! \(user)” statement returns the value of type String and transfers the program to the function call.

greeting stores the value returned from the function. After the function returns, the print statement below the function call executes.

Function with Multiple Parameters and Multiple Return Types

  • Functions can have multiple input parameters, which are written within the function’s parentheses, separated by commas.
  • You can use a tuple type as the return type for a function to return multiple values as part of one compound return value.

Example :

Output :

Good Morning!Jack
You have 0 coins left

In the above program, the function greetUser( ) accepts multiple parameters of type String and Int. To access each return value, we use index positions 0, 1, …

Here, we’ve used msg.0 to access Good Morning!Jack and msg.1 to access 0. But using index values can be unreadable at some time. So we can use names to return values as

Here we can access the result using the variable name as msg.name and msg.coins instead of msg.0 and msg.1.

Keys to remember :

  • Functions can accept parameters — just specify the type of each parameter.
  • Functions can return values, so specify the return type.

Next part: Functions that solve complex problems

“Truth can only be found in one place: the code.”
Robert C. Martin

Find it a good read?

Recommend this post (by clicking 👏 button) so other people can see it too…
reach me on Twitter Sridharan T

--

--