FUNCTION
• A group of statements used to perform a
specific task.
• Functions are self-contained chunks of code that
perform a specific task.
• By defining a function once, you can call it many
times to get your work done.
• Reusability is the benefit of using functions.
FUNCTION
• The syntax of functions in Swift is very flexible.
• Every function in Swift has a type, consisting of
the function’s parameter types and return type.
• It allows you to pass functions as parameters to
other functions and return functions from functions.
• It also allows you to nest the functions(i.e.
encapsulating function inside other function).
DEFINING FUNCTION
• 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.
DEFINING FUNCTION
• By default the arguments/parameters of a
function are immutable.
• But, there is a possibility to change the values of
arguments/parameters by explicitly define them
as mutable.
DEFINING FUNCTION
• Syntax:
func function_name(label parameters) -> returntype
{
statements to be executed..
}
Optional
DEFINING FUNCTION
• Definition Example:
func myFunc()
{
print("Hello")
}
• Calling Example:
myFunc()
PASSING ARGUMENTS IN FUNCTION
func myFunc(name:String)
{
print("Hello "+name)
}
myFunc(name:"John")
OUTPUT
Hello John
Returning values in function
func myFunc (age:Int, height:Int)-> Int
{
return age+height
}
print(myFunc(age:4,height:6))
OUTPUT
10
Function Type
Function Type
• Made up of parameter types and return type of
the function.
• You can use function types just like any other
types in Swift.
• For example, you can define a constant or
variable to be of a function type and assign an
appropriate function to that variable.
• Example: var sum: (Int, Int) -> Int = addTwoInts
print("Result: (sum(2, 3))")
Function Type
• Example:
func add(_ a: Int, _ b: Int) -> Int
{
return a + b
}
var sum: (Int, Int) -> Int = add
print("Result: (sum(2, 3))")
OUTPUT
5
Default arguments in function
func myFunc (age:Int=10,height:Int)-> Int
{
return age+height
}
print(myFunc(age:4,height:6))
print(myFunc(height:6))
OUTPUT
10
16
Function Type
Variadic parameters in function
• A variadic parameter accepts zero or more
values of a specified type.
• You can use variadic parameters when you are
not sure that how many number of arguments are
going to be passed during function call.
• When using varying number of parameters
during function call, for variadic parameters.
• You can access that arguments inside function
body as an array of particular type.
Variadic parameters in function
• Variadic parameters are declared by inserting
three period characters (...) after the parameter’s
type name.
• Example:
func sum(numbers: Int...)
{
statements to be executed
}
Variadic parameters in function
func sum(numbers: Int...) -> Int {
var result = 0
for num in numbers
{ result += num }
return result
}
let sum1 = sum(numbers:1,2)
print(sum1)
let sum2 = sum(numbers:1,2,3,4,5,6)
print(sum2)
OUTPUT
3
21
Returning Multiple Values
func minMax(arr: [Int]) -> (min: Int, max: Int)
{ var currentMin = arr[0]
var currentMax = arr[0]
for n in 0..<arr.count
{ if arr[n] < currentMin
{ currentMin = arr[n] }
else if arr[n] > currentMax
{ currentMax = arr[n] }
} return (currentMin, currentMax)
}
var bounds = minMax(arr: [16, 3, -2, 1, 9, 60])
print("Smallest is (bounds.min)")
print("Largest is (bounds.max)")
OUTPUT
Smallest is -2
Largest is 60
Tuple
Type
func minMax(arr: [Int]) -> (min: Int, max: Int)?
{ if arr.isEmpty
{ return nil }
var currentMin = arr[0]
var currentMax = arr[0]
for n in 0..<arr.count
{ if arr[n] < currentMin
{ currentMin = arr[n] }
else if arr[n] > currentMax
{ currentMax = arr[n] }
} return (currentMin, currentMax)
}
Function Returning
Optional Values
if var bounds = minMax(arr: [16, 3, -2, 1, 9, 60])
{ print("Smallest is (bounds.min)")
print("Largest is (bounds.max)") }
else
{ print("Nothing there to find") }
Function Argument Labels and
Parameter Names
• Each function parameter has both an argument
label and a parameter name.
• The argument label is used when calling the
function.
• Each argument is written in the function call with its
argument label before it.
• The parameter name is used in the implementation
of the function.
Function Argument Labels and
Parameter Names
❖ By default, parameters use their parameter
name as their argument label.
func myFunc(age:Int=10,height:Int)-> Int
{
return age+height
}
print(myFunc(age:4,height:6))
print(myFunc(height:6))
Function Argument Labels and
Parameter Names
❖ All the parameters of a function must have
unique names.
❖ On the other hand, it is possible for multiple
parameters to have the same argument label.
❖ It is not suggested to used same argument
label.
❖ Because, unique argument labels help to
make your code more readable.
Function Argument Labels and
Parameter Names
• Example:
func show(person: String, from city: String) -> String
{
return "Hello (person), from (city)."
}
print(show(person: "Rohit", from: "Alberta"))
OUTPUT
Hello Rohit, from Alberta.
Want to Skipping/Omitting Argument
Labels?
func show(person: String, from city: String) -> String
{
return "Hello (person), from (city)."
}
print(show(person: "Rohit", from: "Alberta"))
func myFunc(age:Int=10,height:Int)-> Int
{
return age+height
}
print(myFunc(age:4,height:6))
print(myFunc(height:6))
Skipping/Omitting Argument Labels
func show(_ person: String, _ city: String)
{
print("Hello (person), from (city). ")
}
show("Rohit", "Alberta")
OUTPUT
Hello Rohit, from Alberta.
Modifying Actual Arguments
func swap( _ a: Int, _ b: Int)
{ a = a + b
b = a - b
a = a - b
}
var (a,b) = (4,6)
print("Before Swap:")
print("(a)t(b)")
swap(a,b)
print("After Swap:")
print("(a)t(b)")
OUTPUT
Error
inout Parameters
• By default the arguments/parameters of a
function are immutable(i.e. constants).
• But, there is a possibility to change the values of
arguments/parameters by explicitly define them
as mutable.
• So, if you want to modify the arguments, you
need to declare them as inout parameters.
inout Parameters Imp.
• In-out parameters cannot have default values.
• Variadic parameters cannot be marked as inout.
• So, if you want to modify the arguments, you
need to declare them as inout parameters.
inout Parameters Syntax
func functionName(label variableName:
inout datatype,…) -> returnType
{
code to modify parameters
}
inout Parameters Implementation
func swap(a: inout Int,b: inout Int)
{ a = a + b
b = a - b
a = a - b
}
var (a,b) = (4,6)
print("Before Swap:")
print("(a)t(b)")
swap(a:&a,b:&b)
print("After Swap:")
print("(a)t(b)")
OUTPUT
Before Swap:
4 6
After Swap:
6 4
Inout parameters Example
func swap(a: inout Int,b: inout Int)
{ var temp = a
a = b
b = temp
}
var (a,b) = (4,6)
print("Before Swap:")
print("(a)t(b)")
swap(a:&a,b:&b)
print("After Swap:")
print("(a)t(b)")
OUTPUT
Error
Note: You can-not use
mutable variables
directly inside a
function
Function Example
func swap(a: inout Int,b: inout Int)
{ let temp = a
a = b
b = temp
}
var (a,b) = (4,6)
print("Before Swap:")
print("(a)t(b)")
swap(a:&a,b:&b)
print("After Swap:")
print("(a)t(b)")
OUTPUT
Before Swap:
4 6
After Swap:
6 4
Nested Functions
• A function defined inside other function is called
a nested function.
• Normally the scope of a function is global.
• But, if you create a nested function, the scope of
the function would be only inside it’s outer
function(i.e. local to function).
Nested Functions
• Example:
func show()
{ func even(_ a:Int)-> Int
{ return a % 2 }
if(even(3)==0)
{ print("Even number") }
else
{ print("Odd number") }
}
show()
OUTPUT
Odd
Nested Function call in parameters
func sum(_ a:Int, _ b:Int) -> Int
{
return a+b
}
func show(_ r:Int)
{
print("Sum is: (r)")
}
show(sum(4,2))
OUTPUT
Sum is: 6
Returning Function from Function
func decr(_ n: Int) -> Int
{ return n – 1 }
func perform() -> (Int) -> Int
{ return decr }
print("Counting to zero:")
var cnt = 3
let down = perform()
while cnt != 0
{ print("got (cnt)")
cnt = down(cnt) }
print("got 0")
OUTPUT
Counting to zero:
got 3
got 2
got 1
got 0
Returning
function from
function
Assigning Function to a variable
func show(a: Int)
{
print("a= (a)")
}
let newFunction = show
newFunction(6)
OUTPUT
a= 6
Recursion(with Function)
func fact(n:Int) -> Int
{
return n==0 ? 1 : n*fact(n:n-1)
}
print(fact(n:5))
OUTPUT
120
Closure
• Closures are self-contained blocks of
functionality.
• It can be passed around and used in your code.
• Closures are un-named block of functionality.
• Closures in Swift are similar to blocks in C and
lambdas in Java, Python, C# or other
languages.
Closure
• Global and Nested Functions are actually special
kind of closures.
• Nested function is a convenient way to name and
define self-contained block within larger
functions.
• Closures and functions are of reference type.
Closure Syntax
{
}
->(parameters) returntype in
Statements to be executed
Closure Example
var add ={
}
->(n1: Int, n2: Int) Int in
return n1 + n2
var result = add(10, 2)
print(result)
OUTPUT
12
Closure Example
Simplest Example:
let show = { print("Hello Closure") }
show()
Closure
OUTPUT
Hello Closure
Empty Closure Example
let arr = { }
print(arr)
OUTPUT
(Function)
Example of Closure
var arr = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
print(arr.count)
print(arr)
let newarr = { arr.remove(at: 0) }
print(arr.count)
print(newarr)
print(newarr())
print(arr.count)
print(arr)
print(newarr())
OUTPUT
5
["Chris", "Alex", "Ewa", "Barry", "Daniella"]
5
(Function)
Chris
4
["Alex", "Ewa", "Barry", "Daniella"]
Alex

10. funtions and closures IN SWIFT PROGRAMMING

  • 1.
    FUNCTION • A groupof statements used to perform a specific task. • Functions are self-contained chunks of code that perform a specific task. • By defining a function once, you can call it many times to get your work done. • Reusability is the benefit of using functions.
  • 2.
    FUNCTION • The syntaxof functions in Swift is very flexible. • Every function in Swift has a type, consisting of the function’s parameter types and return type. • It allows you to pass functions as parameters to other functions and return functions from functions. • It also allows you to nest the functions(i.e. encapsulating function inside other function).
  • 3.
    DEFINING FUNCTION • Everyfunction 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.
  • 4.
    DEFINING FUNCTION • Bydefault the arguments/parameters of a function are immutable. • But, there is a possibility to change the values of arguments/parameters by explicitly define them as mutable.
  • 5.
    DEFINING FUNCTION • Syntax: funcfunction_name(label parameters) -> returntype { statements to be executed.. } Optional
  • 6.
    DEFINING FUNCTION • DefinitionExample: func myFunc() { print("Hello") } • Calling Example: myFunc()
  • 7.
    PASSING ARGUMENTS INFUNCTION func myFunc(name:String) { print("Hello "+name) } myFunc(name:"John") OUTPUT Hello John
  • 8.
    Returning values infunction func myFunc (age:Int, height:Int)-> Int { return age+height } print(myFunc(age:4,height:6)) OUTPUT 10 Function Type
  • 9.
    Function Type • Madeup of parameter types and return type of the function. • You can use function types just like any other types in Swift. • For example, you can define a constant or variable to be of a function type and assign an appropriate function to that variable. • Example: var sum: (Int, Int) -> Int = addTwoInts print("Result: (sum(2, 3))")
  • 10.
    Function Type • Example: funcadd(_ a: Int, _ b: Int) -> Int { return a + b } var sum: (Int, Int) -> Int = add print("Result: (sum(2, 3))") OUTPUT 5
  • 11.
    Default arguments infunction func myFunc (age:Int=10,height:Int)-> Int { return age+height } print(myFunc(age:4,height:6)) print(myFunc(height:6)) OUTPUT 10 16 Function Type
  • 12.
    Variadic parameters infunction • A variadic parameter accepts zero or more values of a specified type. • You can use variadic parameters when you are not sure that how many number of arguments are going to be passed during function call. • When using varying number of parameters during function call, for variadic parameters. • You can access that arguments inside function body as an array of particular type.
  • 13.
    Variadic parameters infunction • Variadic parameters are declared by inserting three period characters (...) after the parameter’s type name. • Example: func sum(numbers: Int...) { statements to be executed }
  • 14.
    Variadic parameters infunction func sum(numbers: Int...) -> Int { var result = 0 for num in numbers { result += num } return result } let sum1 = sum(numbers:1,2) print(sum1) let sum2 = sum(numbers:1,2,3,4,5,6) print(sum2) OUTPUT 3 21
  • 15.
    Returning Multiple Values funcminMax(arr: [Int]) -> (min: Int, max: Int) { var currentMin = arr[0] var currentMax = arr[0] for n in 0..<arr.count { if arr[n] < currentMin { currentMin = arr[n] } else if arr[n] > currentMax { currentMax = arr[n] } } return (currentMin, currentMax) } var bounds = minMax(arr: [16, 3, -2, 1, 9, 60]) print("Smallest is (bounds.min)") print("Largest is (bounds.max)") OUTPUT Smallest is -2 Largest is 60 Tuple Type
  • 16.
    func minMax(arr: [Int])-> (min: Int, max: Int)? { if arr.isEmpty { return nil } var currentMin = arr[0] var currentMax = arr[0] for n in 0..<arr.count { if arr[n] < currentMin { currentMin = arr[n] } else if arr[n] > currentMax { currentMax = arr[n] } } return (currentMin, currentMax) } Function Returning Optional Values if var bounds = minMax(arr: [16, 3, -2, 1, 9, 60]) { print("Smallest is (bounds.min)") print("Largest is (bounds.max)") } else { print("Nothing there to find") }
  • 17.
    Function Argument Labelsand Parameter Names • Each function parameter has both an argument label and a parameter name. • The argument label is used when calling the function. • Each argument is written in the function call with its argument label before it. • The parameter name is used in the implementation of the function.
  • 18.
    Function Argument Labelsand Parameter Names ❖ By default, parameters use their parameter name as their argument label. func myFunc(age:Int=10,height:Int)-> Int { return age+height } print(myFunc(age:4,height:6)) print(myFunc(height:6))
  • 19.
    Function Argument Labelsand Parameter Names ❖ All the parameters of a function must have unique names. ❖ On the other hand, it is possible for multiple parameters to have the same argument label. ❖ It is not suggested to used same argument label. ❖ Because, unique argument labels help to make your code more readable.
  • 20.
    Function Argument Labelsand Parameter Names • Example: func show(person: String, from city: String) -> String { return "Hello (person), from (city)." } print(show(person: "Rohit", from: "Alberta")) OUTPUT Hello Rohit, from Alberta.
  • 21.
    Want to Skipping/OmittingArgument Labels? func show(person: String, from city: String) -> String { return "Hello (person), from (city)." } print(show(person: "Rohit", from: "Alberta")) func myFunc(age:Int=10,height:Int)-> Int { return age+height } print(myFunc(age:4,height:6)) print(myFunc(height:6))
  • 22.
    Skipping/Omitting Argument Labels funcshow(_ person: String, _ city: String) { print("Hello (person), from (city). ") } show("Rohit", "Alberta") OUTPUT Hello Rohit, from Alberta.
  • 23.
    Modifying Actual Arguments funcswap( _ a: Int, _ b: Int) { a = a + b b = a - b a = a - b } var (a,b) = (4,6) print("Before Swap:") print("(a)t(b)") swap(a,b) print("After Swap:") print("(a)t(b)") OUTPUT Error
  • 24.
    inout Parameters • Bydefault the arguments/parameters of a function are immutable(i.e. constants). • But, there is a possibility to change the values of arguments/parameters by explicitly define them as mutable. • So, if you want to modify the arguments, you need to declare them as inout parameters.
  • 25.
    inout Parameters Imp. •In-out parameters cannot have default values. • Variadic parameters cannot be marked as inout. • So, if you want to modify the arguments, you need to declare them as inout parameters.
  • 26.
    inout Parameters Syntax funcfunctionName(label variableName: inout datatype,…) -> returnType { code to modify parameters }
  • 27.
    inout Parameters Implementation funcswap(a: inout Int,b: inout Int) { a = a + b b = a - b a = a - b } var (a,b) = (4,6) print("Before Swap:") print("(a)t(b)") swap(a:&a,b:&b) print("After Swap:") print("(a)t(b)") OUTPUT Before Swap: 4 6 After Swap: 6 4
  • 28.
    Inout parameters Example funcswap(a: inout Int,b: inout Int) { var temp = a a = b b = temp } var (a,b) = (4,6) print("Before Swap:") print("(a)t(b)") swap(a:&a,b:&b) print("After Swap:") print("(a)t(b)") OUTPUT Error Note: You can-not use mutable variables directly inside a function
  • 29.
    Function Example func swap(a:inout Int,b: inout Int) { let temp = a a = b b = temp } var (a,b) = (4,6) print("Before Swap:") print("(a)t(b)") swap(a:&a,b:&b) print("After Swap:") print("(a)t(b)") OUTPUT Before Swap: 4 6 After Swap: 6 4
  • 30.
    Nested Functions • Afunction defined inside other function is called a nested function. • Normally the scope of a function is global. • But, if you create a nested function, the scope of the function would be only inside it’s outer function(i.e. local to function).
  • 31.
    Nested Functions • Example: funcshow() { func even(_ a:Int)-> Int { return a % 2 } if(even(3)==0) { print("Even number") } else { print("Odd number") } } show() OUTPUT Odd
  • 32.
    Nested Function callin parameters func sum(_ a:Int, _ b:Int) -> Int { return a+b } func show(_ r:Int) { print("Sum is: (r)") } show(sum(4,2)) OUTPUT Sum is: 6
  • 33.
    Returning Function fromFunction func decr(_ n: Int) -> Int { return n – 1 } func perform() -> (Int) -> Int { return decr } print("Counting to zero:") var cnt = 3 let down = perform() while cnt != 0 { print("got (cnt)") cnt = down(cnt) } print("got 0") OUTPUT Counting to zero: got 3 got 2 got 1 got 0 Returning function from function
  • 34.
    Assigning Function toa variable func show(a: Int) { print("a= (a)") } let newFunction = show newFunction(6) OUTPUT a= 6
  • 35.
    Recursion(with Function) func fact(n:Int)-> Int { return n==0 ? 1 : n*fact(n:n-1) } print(fact(n:5)) OUTPUT 120
  • 36.
    Closure • Closures areself-contained blocks of functionality. • It can be passed around and used in your code. • Closures are un-named block of functionality. • Closures in Swift are similar to blocks in C and lambdas in Java, Python, C# or other languages.
  • 37.
    Closure • Global andNested Functions are actually special kind of closures. • Nested function is a convenient way to name and define self-contained block within larger functions. • Closures and functions are of reference type.
  • 38.
  • 39.
    Closure Example var add={ } ->(n1: Int, n2: Int) Int in return n1 + n2 var result = add(10, 2) print(result) OUTPUT 12
  • 40.
    Closure Example Simplest Example: letshow = { print("Hello Closure") } show() Closure OUTPUT Hello Closure
  • 41.
    Empty Closure Example letarr = { } print(arr) OUTPUT (Function)
  • 42.
    Example of Closure vararr = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] print(arr.count) print(arr) let newarr = { arr.remove(at: 0) } print(arr.count) print(newarr) print(newarr()) print(arr.count) print(arr) print(newarr()) OUTPUT 5 ["Chris", "Alex", "Ewa", "Barry", "Daniella"] 5 (Function) Chris 4 ["Alex", "Ewa", "Barry", "Daniella"] Alex