HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
10. funtions and closures IN SWIFT PROGRAMMING
1. 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.
2. 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).
3. 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.
4. 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.
7. PASSING ARGUMENTS IN FUNCTION
func myFunc(name:String)
{
print("Hello "+name)
}
myFunc(name:"John")
OUTPUT
Hello John
8. Returning values in function
func myFunc (age:Int, height:Int)-> Int
{
return age+height
}
print(myFunc(age:4,height:6))
OUTPUT
10
Function Type
9. 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))")
10. 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
11. 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
12. 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.
13. 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
}
14. 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
15. 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
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 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.
18. 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))
19. 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.
20. 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.
21. 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))
23. 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
24. 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.
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.
27. 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
28. 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
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
• 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).
32. 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
33. 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
34. Assigning Function to a variable
func show(a: Int)
{
print("a= (a)")
}
let newFunction = show
newFunction(6)
OUTPUT
a= 6
36. 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.
37. 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.