Swift Functions

  Total Views : 253
  Comments : 0
  Keywords : Swift functions are the code blocks to perform defined tasks and return data, Swift functions to improve code re-usability and return value by executing specified statements.

Here we will learn functions in swift with examples and how to use swift functions to execute specified statements and return value, functions with multiple parameters and return types, function with argument labels and parameters, send function as a variable, swift functions with variadic parameters and nested functions with examples.

Swift Functions

In swift functions are the block of statements to perform specified tasks and return values based on our defined conditions.

 

In swift we can send data to functions by using input parameters and functions is having return types to return data as result.

 

Generally in swift, functions will help us to improve the code re-usability like suppose if we have requirement like implementing the same functionality in multiple places of an application then we can create single function with the required code in separate file and call that function in our application wherever it required and by doing this automatically the duplicate code in our application will get reduced.

Syntax of Swift Functions

In swift the declaration of function syntax will be same as other programming languages but only difference is return type must be declare in parameters side.

 

In swift functions the declaration of parameters and return type are not a mandatory and by using “func” keyword we can define functions.

 

Following is the syntax of defining or declaring functions in swift programming language.

 

func functionName(parameters) -> Returntype {

//Statements

return parameters

}

If you observe above swift functions syntax we defined few parameters those are

 

func – It’s a keyword which is used to define function in swift programming language.

 

functionName – Its name of the function which we are going to create in application.

 

parameters – These are the input parameters to pass data to functions and its optional.

 

-> - The hyphen followed by a right angle bracket indicates return type of function in swift.

 

Returntype – It indicates return type of the function.

 

Now we will see how to use functions in swift programming language with examples.

Swift Function Example

Following is the example of creating functions and use it in swift programming language.

 

func helloworld(x: String, y: String) -> String {

return x + " " + y

}

print(helloworld("Welcome", "to Tutlane"))

If you observe above function its simple function in swift programming language with return type.

 

When we run above program in swift playground we will get result like as shown below.

 

Welcome to Tutlane

Now we will see how to pass parameters and return types to the function in swift programming language with examples.

Swift Function with Parameters and Return Types

In swift, functions will accept input parameters and return values based on our requirements. The input parameters and return values are optional in swift functions.

 

Now we will see how to use parameters and return types in swift programming language based on our requirements with examples.

Swift Function without Parameters

Generally in swift functions it’s not a mandatory to define input parameters. Following is the example of defining function without having any parameters in swift programming language.

 

func helloworld() {

print("Welcome to Tutlane")

}

helloworld()

If you observe above example we defined function without having any input parameters and return types in swift programming language.

 

When we run above program in swift playground we will get result like as shown below

 

Welcome to Tutlane

Now we will see how to use functions with multiple parameters in swift programming language.

Swift Function with Multiple Parameters

In swift functions we can send multiple input parameters based on our requirements.

 

Following is the example of sending single parameter to the function in swift programming language.

 

func addition(a: Int) {

print("\(a) + 50 = \(a + 50)")

}

addition(120)

In above example we are sending only one parameter to the function in swift programming language. 

 

When we run above program in swift playground we will get result like as shown below

 

120 + 50 = 170

Following is the example of sending multiple parameters to function in swift programming language.

 

func Multiplication(x: Int, y: Int) {

print("\(x) * \(y) = \(x * y)")

}

Multiplication(100, 50)

If you observe above example we defined multiple parameters (x, y) in function.

 

When we run above example in swift playground we will get result like as shown below.

 

100 * 50 = 5000

Now we will see how to use return types in swift functions based on our requirements.

Swift Function without Return Values

As we discussed, in swift functions return types are an optional. We can create functions without having any return type values based on our requirements in swift programming language. 

 

Following is the example of creating function without return type in swift programming language.

 

func helloworld(x: String, y: String) {

print(x + " " + y)

}

helloworld("Welcome", "to Tutlane")

If you observe above example we defined function without having any return types.

 

When we run above example in swift playground we will get result like as shown below

 

Welcome to Tutlane

This is how we can create functions without return types in swift programming language.

Swift Function with Multiple Return Values

In Swift, by using tuple type as a function return type we can return multiple values as a part of one compound return value based on our requirements.

 

Following is the syntax of declaring function with multiple return values in swift.

 

func funcName() -> (Datatype, Datatype) {

return ( ArgumentName1, ArgumentName2)

}

In above syntax we defined multiple return types in function and returning those values based on our requirements.

 

Following is the example of returning multiple values from function in swift programming language.

 

func getFullName() -> (String, String) {

var FirstName = "Welcome to"

var LastName = "Tutlane"

return ( FirstName, LastName)

}

var vals = getFullName()

print(vals.0 + " " +vals.1)

If you observe above example we are returning multiple values from function ”getFullName” and holding those values in one variable called “vals” and accessing those values using variable “vals

 

When we run above example in swift playground we will get result like as shown below

 

Welcome to Tutlane

This is how we can create functions with multiple return types in swift programming language.

Swift Function with Default Parameter Values

In swift we can define a default value for any parameter in a function by assigning a value to the parameter after the parameter’s type.

 

If we define default value for parameter we can omit that parameter while calling the function in swift programming language.

 

Following is the syntax of declaring a function with default parameter values in swift.

 

func funcName(param1: Datatype, param2: Datatype = defaultValue)->Datatype {

return param1 + param2

}

If you observe above syntax we assigned default value to the parameter “param2” after the type of parameter.

 

Now we will see how to set default values to the parameters in swift functions with examples.

 

Following is the example of assigning a default values to the parameters in swift functions.

 

func addition(num1: Int, num2: Int = 45)->Int {

return num1 + num2

}

print("23 + 45  = \(addition(23))")

If you observe above example we assigned default value “45” to the parameter “num2” and accessing those values by calling function “addition” with single parameter.

 

When we run above program in swift playground we will get result like as shown below.

 

23 + 45 = 68

This is how we can assign default values to the parameters in swift programming language.

Swift Function Parameters Handling

In swift when we define a parameter in a function, compiler will treat parameters are like constants and it won’t allow us to make any changes to the parameter values. In case if we try to perform increment or decrement operation on function parameter values then we will get an error.

 

Following is the example of changing the function parameter value in swift programming language.

 

func increment(val: Int) {

val++

print(val)

}

print(increment(10, 90))

If you observe above example we are trying to increment function parameter “val”. 

 

When we run above program we will get error like as shown below

 

error: unary operator '++' cannot be applied to an operand of type 'Int'

In case if we want to modify function parameter values in swift then we need to define parameter in function with var keyword.

 

Following is the example of defining function parameters with “var” keyword to modify parameter values in swift programming language.

 

func increment(var val: Int) {

val++

print(val)

}

increment(2)

If you observe above example we defined function parameter “val” with “var” keyword to modify parameter value in swift functions.

 

When we run above program in swift playground we will get result like as shown below.

 

3

This is how we can modify parameter values of function in swift programming language.

Swift Function with Variadic Parameter

In swift variadic parameter accepts zero or more values of a specified type. By using variadic parameter we can specify that the parameter can be passed a varying number of input values when the function is called. 

 

We can use variadic parameters by inserting three dot characters (...) after the parameter’s type name.

 

Following is the example of using variadic parameters in function declaration in swift programming language.

 

func additionofnumber(_ numbers: Int...) -> Int {

var sum: Int = 0

for num in numbers {

sum += num

}

return sum

}

print(additionofnumber(2123233445,55,66))

If you observe above example we defined variadic parameter “numbers” with three dot characters (…) to send multiple values as a input.

 

When we run above program in swift playground we will get the result like as shown below

 

267

This is how we can use variadic parameters in function parameters declaration to send multiple values in swift programming language.

Swift Function with Argument Labels and Parameters Names

In swift we can define function parameters with both argument labels and parameter names. We can use argument labels as a parameter names while sending value to the function.

 

Generally in swift functions we can define argument label names just before while defining parameter names and the parameters names used in implement of function and argument label names used to send values.

 

Following is the example of sending values to the function with argument labels names in swift programming language.

 

func addition(param1 num1: Int, param2 num2: Int = 45)->Int {

var sum = num1 + num2

return sum

}

print("23 + 45  = \(addition(param1: 23, param2: 45))")

If you observe above example we defined argument labels (param1, param2) just before the parameter names in function definition and we are using argument label names to send values to the function.

 

When we run above program in swift playground we will get the result like as shown below

 

23 + 45 = 68

This is how we can use argument labels in function parameters declaration based on requirements in swift programming language.

Swift Functions Omit Argument Labels

If we don’t want to use argument label in swift functions then we can define function parameter with underscore (_) instead of explicit argument label for that parameter.

 

Following is the example of sending values to the function with argument labels names in swift programming language.

 

func addition(_ num1: Int, num2: Int = 45)->Int {

var sum = num1 + num2

return sum

}

print("23 + 45  = \(addition(23, num2: 45))")

If you observe above example we defined underscore just before the parameter num1 name to ignore argument label for that parameter in function definition and we are sending values to the function without argument label name.

 

When we run above program in swift playground we will get the result like as shown below

 

23 + 45 = 68

This is how we can ignore argument labels in function parameters declaration based on requirements in swift programming language.

 

Note: If we define parameters in function with argument labels then the argument labels must be labeled when we call the function. 

Swift Assign Function to Variable

In swift we can assign function to a variable or constant based on our requirements. To assign function to a variable we need to define variables parameter type and return type must be same as function. 

 

Following is the syntax of assigning function to a variable in swift programming language.

 

func funcName(param1: Datatype, param2: Datatype) -> Datatype {

return param1,param2

}

var variablename: (Datatype, Datatype) -> Datatype = funcName

variablename(value1, value2)

If you observe above syntax we defined a function “funcName” and assigned function “funcName” to a variable variablename by defining parameters and data types same as function.

 

Following is the example of assigning function to a variable in swift programming language.

 

func add(a: Int, b: Int) -> Int {

return a + b

}

var addition: (Int, Int) -> Int = add

print("10 + 90  = \(addition(10, 90))")

When we run above program in swift playground we will get result like as shown below

 

10 + 90 = 100

This is how we can assign a function to the variable in swift programming language.

Swift Nested Functions 

In swift the functions which are inside the body of other functions known as nested functions.

 

In swift by default nested functions are hidden from the outside world but we can use those nested functions by their enclosing functions.

 

An enclosing function can return nested functions to allow the nested function to be used in another scope.

 

Following is the example of using nested functions in swift programming language.

 

func addoperation(str:String) -> (Int,Int)->Int {

func sum(a:Int,b:Int)->Int

{

return a+b;

}

if str == "+"

{

return sum;

}

return sum

}

let nestedVal = addoperation("+")

print(nestedVal(10,30))

If you observe above example we defined function “sum” inside of another function “addoperation” and performing sum operation by passing values to main function addoperation().

 

When we run above example in swift playground we will get result like as shown below.

 

40

This is how we can use functions to perform operations based on our requirements in swift programming language. 

 
 

NEXT

Swift Closures  
 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User