Swift Function Parameters and Return Values
A function is a piece of code that is used to perform some specific task. Just like other programming languages Swift also has functions and the function has its name, parameter list, and return value. Their syntax is flexible enough to create simple as well as complex functions. All the functions in the Swift have a type, which makes the function a lot easier to pass a function as a parameter to another function or return a function from another function or create nested functions. A function is defined using the func keyword. And you can call a function simply by its name.
Syntax:
func functionName(ParameterName: type) ->returnType{
// Body of the function
}
Now we will discuss how the function works with or without parameters and return values.
Function Without Parameters and Return Value
In Swift, a function can be defined without parameters and return value. This function returns the same value whenever they are called. The function definition still requires empty parentheses with the name even when the function is called.
Syntax:
func functionName(){
// Function body
}
Example:
Swift
// Swift program to illustrate Function Without Parameters // and Return Value import Swift // Creating a function // Without any parameter and return value func w3wiki(){ print ( "Lets learn something new!!" ) } // Calling the function w3wiki() |
Output:
Lets learn something new!!
Function With Return Value and Without Parameter
In Swift, a function can be defined with a return value and without a parameter. Such type of function returns the same type of value whenever they are called and cannot allow control to leave the bottom of the function without returning a value if it tries to do then you will get a compile-time error. The function definition still requires empty parentheses followed by a return type and we can call such type of function with their name followed by empty parentheses.
Syntax:
func functionName()->ReturnValue{
// Function body
}
Example:
Swift
// Swift program to illustrate Function With Return Value // and Without Parameter import Swift // Creating a function with return value // and without Parameter func w3wiki() -> String { return "Lets learn something new!!" } // Calling the function let display = w3wiki() // Displaying the results print (display) |
Output:
Lets learn something new!!
Function With Parameter and Without Return Value
In Swift, a function can be defined with a parameter and without a return value. Such type of function does not contain a return value in the function definition. Although such type of function is not defined with a return value, still they will return a special value of void type. When we call such type of function the return value can be ignored.
Syntax:
func functionName(parameterName: type){
// Function body
}
Example:
Swift
// Swift program to illustrate Function With Parameter import Swift // Creating a function with parameter func w3wiki(stat: String ){ print (stat) } // Calling the function w3wiki(stat: "Lets learn something new!!" ) |
Output:
Lets learn something new!!
Function With a Parameter and Return Value
In Swift, a function can be defined with a parameter and a return value. Such type of function definition contains both parameters and the return value. Here the return value of the function can’t be ignored and cannot allow control to leave the bottom of the function without returning a value if it tries to do then you will get a compile-time error. It is not necessary that the parameter data type and the return type are similar.
Syntax:
func functionName(parameterName: type) -> returnValue{
// Function body
}
Example:
Swift
// Swift program to illustrate Function With // parameter and return value import Swift // Creating a function with parameter // and return value func w3wiki(bonus: Int ) -> Int { let empsalary = bonus + 20000 return empsalary } // Calling the function var updatedData = w3wiki(bonus: 1000) // Display the updated salary print ( "New salary: " , updatedData) |
Output:
New salary: 21000
Function With Multiple Parameters and Single Return Value
In Swift, a function can be defined with multiple parameters and a return value. In such type of function, the definition contains multiple parameters separated by commas in the parentheses and the return value.
Syntax:
func functionName(parameterName1: type, parameterName2: type, parameterName3: type) -> returnValue{
// Function body
}
Example:
Swift
// Swift program to illustrate Function With // multiple parameters and a return value import Swift // Creating a function with multiple parameters // and a return value func w3wiki(newArticle: Int , OldArticle: Int ) -> Int { let ArticleCount = newArticle + OldArticle return ArticleCount } // Calling the function var updatedData = w3wiki(newArticle: 30, OldArticle: 230) // Display the updated data print ( "Total count of the Articles: " , updatedData) |
Output:
Total count of the Articles: 260
Function With Single Parameter and Multiple Return Values
In Swift, a function can be defined with a parameter and multiple return values. In such type of function, the definition contains a parameter and multiple return values separated by commas in the parentheses. Here Swift uses tuple type as a return type to return multiple values as a part of a single unit or compound. In the tuple, we can also provide the label to each return value so that they can be further accessed using their name with the help of dot syntax. Also, remember we do not need to provide the names of the tuple members when they are returned from the function because their names are already specified in the return type part of the function.
Syntax:
func functionName(parameterName: type) -> (returnValueName1: type, returnValueName2: type, returnValueName3: type){
// Function body
}
Example:
Swift
// Swift program to illustrate Function With // a parameter and multiple return values import Swift // Creating a function with a parameter // and multiple return values. // This function is used to find the minimum // and maximum salary of the employees func w3wiki(ESalary: [ Int ]) -> (minSalary: Int , maxSalary: Int ){ // Creating two variables that contains the // value of first integer in the array var MinValue = ESalary[0] var MaxValue = ESalary[0] // Iterate the array to find the minimum // and maximum value for newValue in ESalary[1..<ESalary. count ]{ if newValue < MinValue{ MinValue = newValue } if newValue > MaxValue{ MaxValue = newValue } } // Returning the minimum and maximum values // that we find from the array return (MinValue, MaxValue) } // Calling the function var updatedData = w3wiki(ESalary: [23000, 15000, 450000, 50000, 12000]) // Display the minimum salary print ( "Minimum salary of the GEmployee: " , updatedData.minSalary) // Display the maximum salary print ( "Maximum salary of the GEmployee: " , updatedData.maxSalary) |
Output:
Minimum salary of the GEmployee: 12000 Maximum salary of the GEmployee: 450000
Function With Multiple Parameters and Return Values
In Swift, a function can be defined with multiple parameters and return values. In such type of function, the definition contains multiple parameters and return values separated by commas in the parentheses. Here Swift uses tuple type as a return type to return multiple values as a part of a single unit or compound. In the tuple, we can also provide the label to each return value so that they can be further accessed using their name with the help of dot syntax.
Syntax:
func functionName(parameterName1: type, parameterName2: type, parameterName3: type) -> (returnValueName1: type, returnValueName2: type, returnValueName3: type){
// Function body
}
Example:
Swift
// Swift program to illustrate Function With // multiple parameters and return values import Swift // Creating a function with multiple parameters // and multiple return values. func w3wiki(EName: String , EAge: Int , ESalary: Int ) -> (FullName: String , CurrentAge: Int , CurrentSalary: Int ){ // Updating old data let FullName = EName + " Singh" let NewAge = EAge + 1 let NewSalary = ESalary + 2000 // Returning multiple values return (FullName, NewAge, NewSalary) } // Calling the function var updatedData = w3wiki(EName: "Sumit" , EAge: 23, ESalary: 23000) // Display the full name print ( "Full name of the GEmployee: " , updatedData.FullName) // Display the current age print ( "Current age of the GEmployee: " , updatedData.CurrentAge) // Display the current salary print ( "Current salary of the GEmployee: " , updatedData.CurrentSalary) |
Output:
Full name of the GEmployee: Sumit Singh Current age of the GEmployee: 24 Current salary of the GEmployee: 25000
Function With Optional Tuple Return Type
In Swift, a function can be defined with an optional tuple return type. In such type of function, a tuple type will be returned from a function that has no value for the entire tuple or we can say that the entire tuple is nil. In a function definition, to define an optional tuple return type simply place a question mark after the parenthesis is closed(as shown in the below syntax).
Syntax:
func functionName(parameterName: type) ->(returnValueName1: type, returnValueName2: type)? {
// Function body
}
Always remember optional tuple type for example(String, String)? is different from the tuple that holds optional types for example(string?, string?). Here the whole tuple is optional not the individual value in the tuple. The use of optional tuple return type is explained in the below example. In the below example, if we do not use an optional tuple return type then we will get an error while attempting to access ESalary[0]. To handle empty arrays safely we use an optional tuple return type.
Example:
Swift
// Swift program to illustrate Function With // Optional Tuple Return Type import Swift // Creating a function with Optional Tuple Return Type // This function will return nil when the given array is empty func w3wiki(ESalary: [ Int ]) -> (minSalary: Int , maxSalary: Int )?{ // If the given array is empty then return nil if ESalary.isEmpty { return nil } // Creating two variables that contains the // value of first integer in the array var MinValue = ESalary[0] var MaxValue = ESalary[0] // Iterate the array to find the minimum // and maximum value for newValue in ESalary[1..<ESalary. count ]{ if newValue < MinValue{ MinValue = newValue } if newValue > MaxValue{ MaxValue = newValue } } // Returning the minimum and maximum data // that we find from the ESalary array return (MinValue, MaxValue) } // Calling the function var updatedData = w3wiki(ESalary: []) print ( "Given array : " , updatedData) |
Output:
Given array : nil
Function With an Implicit Return Type
In Swift, the whole body of the function can be defined as a single expression. Such a type of function implicitly returns the specified expression. You are allowed to remove the return keyword if the function is written as one return line. Always remember the implicit return value must return something. You are not allowed to use simply print(“w3wiki”) as an implicit return value although you can use functions that never return as an implicit return value, for example, fatalError(), etc.
Syntax:
func functionName(parameterName: type) -> returnValue{
// Expression
}
Example:
Swift
// Swift program to illustrate Function With an Implicit Return Type import Swift // Creating a function with an Implicit Return Type func w3wiki( for EAuthor: String ) -> String { "Geek of the Month is " + EAuthor + " !!Congratulations!!" } // Calling the function and displaying the final result print (w3wiki( for : "Mohit" )) |
Output:
Geek of the Month is Mohit !!Congratulations!!