SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements Tarun Sharma
 
Binary operator overloading
Binary operator overloadingBinary operator overloading
Binary operator overloadingBalajiGovindan5
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++Neeru Mittal
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in SwiftSaugat Gautam
 
String functions and operations
String functions and operations String functions and operations
String functions and operations Mudasir Syed
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - OperatorsWebStackAcademy
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONvikram mahendra
 
Windows form application - C# Training
Windows form application - C# Training Windows form application - C# Training
Windows form application - C# Training Moutasm Tamimi
 
C++ Function
C++ FunctionC++ Function
C++ FunctionHajar
 
Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)VC Infotech
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword pptVinod Kumar
 

Was ist angesagt? (20)

Python ppt
Python pptPython ppt
Python ppt
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
Binary operator overloading
Binary operator overloadingBinary operator overloading
Binary operator overloading
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Enums in c
Enums in cEnums in c
Enums in c
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
String functions and operations
String functions and operations String functions and operations
String functions and operations
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
 
functions of C++
functions of C++functions of C++
functions of C++
 
Windows form application - C# Training
Windows form application - C# Training Windows form application - C# Training
Windows form application - C# Training
 
C functions
C functionsC functions
C functions
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
C program compiler presentation
C program compiler presentationC program compiler presentation
C program compiler presentation
 

Ähnlich wie 10. funtions and closures IN SWIFT PROGRAMMING

Reference Parameter, Passing object by reference, constant parameter & Defaul...
Reference Parameter, Passing object by reference, constant parameter & Defaul...Reference Parameter, Passing object by reference, constant parameter & Defaul...
Reference Parameter, Passing object by reference, constant parameter & Defaul...Meghaj Mallick
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdfNehaSpillai1
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptRajasekhar364622
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxsangeeta borde
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default argumentsNikhil Pandit
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptxRhishav Poudyal
 
functionsinc-130108032745-phpapp01.pdf
functionsinc-130108032745-phpapp01.pdffunctionsinc-130108032745-phpapp01.pdf
functionsinc-130108032745-phpapp01.pdfmounikanarra3
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptxSulekhJangra
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with SwiftFatih Nayebi, Ph.D.
 

Ähnlich wie 10. funtions and closures IN SWIFT PROGRAMMING (20)

Function
FunctionFunction
Function
 
Reference Parameter, Passing object by reference, constant parameter & Defaul...
Reference Parameter, Passing object by reference, constant parameter & Defaul...Reference Parameter, Passing object by reference, constant parameter & Defaul...
Reference Parameter, Passing object by reference, constant parameter & Defaul...
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 
Functions
FunctionsFunctions
Functions
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
functionsinc-130108032745-phpapp01.pdf
functionsinc-130108032745-phpapp01.pdffunctionsinc-130108032745-phpapp01.pdf
functionsinc-130108032745-phpapp01.pdf
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with Swift
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Lecture6
Lecture6Lecture6
Lecture6
 
Review functions
Review functionsReview functions
Review functions
 
Function
Function Function
Function
 

Mehr von LOVELY PROFESSIONAL UNIVERSITY

Mehr von LOVELY PROFESSIONAL UNIVERSITY (19)

Enumerations, structure and class IN SWIFT
Enumerations, structure and class IN SWIFTEnumerations, structure and class IN SWIFT
Enumerations, structure and class IN SWIFT
 
Dictionaries IN SWIFT
Dictionaries IN SWIFTDictionaries IN SWIFT
Dictionaries IN SWIFT
 
Control structures IN SWIFT
Control structures IN SWIFTControl structures IN SWIFT
Control structures IN SWIFT
 
Arrays and its properties IN SWIFT
Arrays and its properties IN SWIFTArrays and its properties IN SWIFT
Arrays and its properties IN SWIFT
 
Array and its functionsI SWIFT
Array and its functionsI SWIFTArray and its functionsI SWIFT
Array and its functionsI SWIFT
 
practice problems on array IN SWIFT
practice problems on array IN SWIFTpractice problems on array IN SWIFT
practice problems on array IN SWIFT
 
practice problems on array IN SWIFT
practice problems on array  IN SWIFTpractice problems on array  IN SWIFT
practice problems on array IN SWIFT
 
practice problems on array IN SWIFT
practice problems on array IN SWIFTpractice problems on array IN SWIFT
practice problems on array IN SWIFT
 
practice problems on functions IN SWIFT
practice problems on functions IN SWIFTpractice problems on functions IN SWIFT
practice problems on functions IN SWIFT
 
Variables and data types IN SWIFT
 Variables and data types IN SWIFT Variables and data types IN SWIFT
Variables and data types IN SWIFT
 
Soft skills. pptx
Soft skills. pptxSoft skills. pptx
Soft skills. pptx
 
JAVA
JAVAJAVA
JAVA
 
Unit 5
Unit 5Unit 5
Unit 5
 
Unit 4
Unit 4Unit 4
Unit 4
 
Unit 3
Unit 3Unit 3
Unit 3
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Unit 1
Unit 1Unit 1
Unit 1
 
COMPLETE CORE JAVA
COMPLETE CORE JAVACOMPLETE CORE JAVA
COMPLETE CORE JAVA
 
Data wrangling IN R LANGUAGE
Data wrangling IN R LANGUAGEData wrangling IN R LANGUAGE
Data wrangling IN R LANGUAGE
 

Kürzlich hochgeladen

SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 

Kürzlich hochgeladen (20)

SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
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.
  • 5. DEFINING FUNCTION • Syntax: func function_name(label parameters) -> returntype { statements to be executed.. } Optional
  • 6. DEFINING FUNCTION • Definition Example: func myFunc() { print("Hello") } • Calling Example: myFunc()
  • 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))
  • 22. Skipping/Omitting Argument Labels func show(_ person: String, _ city: String) { print("Hello (person), from (city). ") } show("Rohit", "Alberta") OUTPUT Hello Rohit, from Alberta.
  • 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.
  • 26. inout Parameters Syntax func functionName(label variableName: inout datatype,…) -> returnType { code to modify 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).
  • 31. 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
  • 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
  • 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 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.
  • 38. Closure Syntax { } ->(parameters) returntype in Statements to be executed
  • 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: let show = { print("Hello Closure") } show() Closure OUTPUT Hello Closure
  • 41. Empty Closure Example let arr = { } print(arr) OUTPUT (Function)
  • 42. 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