Functions in Swift

A function is a block of code that can be executed as many times as you want.

In swift a function is defined by “func” keyword. When a function is declared based on requirement it may take one or more parameter, process it and return the valueFunction with no parameters and no return value.

Function with no parameter and no return type.

Syntax:
func function_name() {
--
}
func addTwoNumbers() {
let a = 1
let b = 2
let c = a+b
print(c)  // 3
}

addTwoNumbers() 

If you are not sure why I’ve written let and not var you should check my tutorial on let vs var

Function with no parameter and return type

 Syntax:
func function_name() -> Data Type {
--
return some values
}
func addTwoNumbers()->Int {
let a = 1
let b = 2
let c = a+b
return c 
}

let sum = addTwoNumbers()
print(sum) // 3

Function with parameter and return type

Syntax: 
func function_name(arguments parameter_name: Data Type) -> Data Type { 
------
return some values
}
func addTwoNumbers(arg param: Int)->Int {
let a = param
let b = 2
let c = a+b
return c
}

let sum = addTwoNumbers(arg: 4)
print(sum) // 6

Alternately you can skip the arg and directly pass the value to the function.

func addTwoNumbers(param: Int)->Int {
let a = param
let b = 2
let c = a+b
return c
}

let sum = addTwoNumbers(param: 4)
print(sum) // 6

Function with parameter and no return type

Syntax: 
func function_name(arguments parameter_name: Data Type)  {
----
 return some values
}
func addTwoNumbers(arg param: Int){
let a = param
let b = 2
let c = a+b
print(c)  //6
}
addTwoNumbers(arg: 4)

So this was introduction to functions in Swift. In the next tutorial we will be seeing closures and completion handlers.

Leave a comment