SlideShare una empresa de Scribd logo
1 de 23
Descargar para leer sin conexión
Unit 5—Lesson 1:
Closures
Closures
let sortedTracks = tracks.sorted ( )
(firstTrack: Track, secondTrack: Track) -> Bool in
return firstTrack.trackNumber < secondTrack.trackNumber
Syntax
func sum(numbers: [Int]) -> Int {
// Code that adds together the numbers array
return total
}
let sumClosure = { (numbers: [Int]) -> Int in
// Code that adds together the numbers array
return total
}
// A closure with no parameters and no return value
let printClosure = { () -> Void in
print("This closure does not take any parameters and does not return a value.")
}

// A closure with parameters and no return value
let printClosure = { (string: String) -> Void in
print(string)
}
// A closure with no parameters and a return value
let randomNumberClosure = { () -> Int in
// Code that returns a random number
}
// A closure with parameters and a return value
let randomNumberClosure = { (minValue: Int, maxValue: Int) -> Int in
// Code that returns a random number between `minValue` and `maxValue`
}
Passing closures as arguments
let sortedTracks = tracks.sorted { (firstTrack: Track, secondTrack: Track) -> Bool in
return firstTrack.trackNumber < secondTrack.trackNumber
}
let sortedTracks = tracks.sorted { (firstTrack: Track, secondTrack: Track) -> Bool in
return firstTrack.starRating < secondTrack.starRating
}
Syntactic sugar
let sortedTracks = tracks.sorted { (firstTrack: Track, secondTrack: Track) -> Bool in
return firstTrack.starRating < secondTrack.starRating
}
Syntactic sugar
let sortedTracks = tracks.sorted { (firstTrack, secondTrack) -> Bool in
return firstTrack.starRating < secondTrack.starRating
}
Syntactic sugar
let sortedTracks = tracks.sorted { (firstTrack, secondTrack) in
return firstTrack.starRating < secondTrack.starRating
}
Syntactic sugar
let sortedTracks = tracks.sorted { return $0.starRating < $1.starRating }
Syntactic sugar
let sortedTracks = tracks.sorted { $0.starRating < $1.starRating }
Collection functions using closures
Map

Filter

Reduce
Collection functions using closures
// Initial array
let firstNames = ["Johnny", "Nellie", "Aaron", "Rachel"]
// Creates an empty array that will be used
// to store the full names
var fullNames: [String] = []
for name in firstNames {
let fullName = name + " Smith"
fullNames.append(fullName)
}
0 "Johnny Smith"
1 "Nellie Smith"
2 "Aaron Smith"
3 "Rachel Smith"
fullNames
Collection functions using closures
// Initial array
let firstNames = ["Johnny", "Nellie", "Aaron", "Rachel"]
// Creates a new array of full names by adding "Smith"
// to each first name
let fullNames = firstNames.map { (name) -> String in
return name + " Smith"
}
0 "Johnny Smith"
1 "Nellie Smith"
2 "Aaron Smith"
3 "Rachel Smith"
fullNames
Collection functions using closures
// Initial array
let firstNames = ["Johnny", "Nellie", "Aaron", "Rachel"]
// Creates a new array of full names by adding "Smith"
// to each first name
let fullNames = firstNames.map{ $0 + " Smith" }
0 "Johnny Smith"
1 "Nellie Smith"
2 "Aaron Smith"
3 "Rachel Smith"
fullNames
Collection functions using closures
let numbers = [4, 8, 15, 16, 23, 42]
var numbersLessThan20: [Int] = []
for number in numbers {
if number < 20 {
numbersLessThan20.append(number)
}
}
0 4
1 8
2 15
3 16
numbersLessThan20
Collection functions using closures
let numbers = [4, 8, 15, 16, 23, 42]
let numbersLessThan20 = numbers.filter { (number) -> Bool in
return number < 20
}
0 4
1 8
2 15
3 16
numbersLessThan20
Collection functions using closures
let numbers = [4, 8, 15, 16, 23, 42]
let numbersLessThan20 = numbers.filter{ $0 < 20 }
0 4
1 8
2 15
3 16
numbersLessThan20
Collection functions using closures
let numbers = [8, 6, 7, 5, 3, 0, 9]
var total = 0
for number in numbers {
total = total + number
}
Collection functions using closures
let numbers = [8, 6, 7, 5, 3, 0, 9]
let total = numbers.reduce(0) { (currentTotal, newValue) -> Int in
return currentTotal + newValue
}
Collection functions using closures
let numbers = [8, 6, 7, 5, 3, 0, 9]
let total = numbers.reduce(0,{ $0 + $1})
Closures capture their environment
animate {
self.view.backgroundColor = .red
}
Lab: Closures
Unit 5—Lesson 1
Open and complete the exercises in Lab - Closures.playground
© 2017 Apple Inc. 

This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.

Más contenido relacionado

La actualidad más candente

Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a ElixirSvet Ivantchev
 
Creating a Table from a Function
Creating a Table from a FunctionCreating a Table from a Function
Creating a Table from a Functiondmidgette
 
The Chain Rule, Part 2
The Chain Rule, Part 2The Chain Rule, Part 2
The Chain Rule, Part 2Pablo Antuna
 
How fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practiceHow fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practiceTobias Pfeiffer
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиMaxim Kulsha
 
Functional perl
Functional perlFunctional perl
Functional perlErrorific
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetSamuel Lampa
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Baruch Sadogursky
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonCarlos V.
 
Analytics functions in mysql, oracle and hive
Analytics functions in mysql, oracle and hiveAnalytics functions in mysql, oracle and hive
Analytics functions in mysql, oracle and hiveAnkit Beohar
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cythonAnderson Dantas
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
 
Lecture5 my sql statements by okello erick
Lecture5 my sql statements by okello erickLecture5 my sql statements by okello erick
Lecture5 my sql statements by okello erickokelloerick
 

La actualidad más candente (20)

Codigos
CodigosCodigos
Codigos
 
Unix prog
Unix progUnix prog
Unix prog
 
Py3k
Py3kPy3k
Py3k
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Creating a Table from a Function
Creating a Table from a FunctionCreating a Table from a Function
Creating a Table from a Function
 
The Chain Rule, Part 2
The Chain Rule, Part 2The Chain Rule, Part 2
The Chain Rule, Part 2
 
How fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practiceHow fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practice
 
Slides
SlidesSlides
Slides
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
Functional perl
Functional perlFunctional perl
Functional perl
 
Erlang
ErlangErlang
Erlang
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat Sheet
 
1 pythonbasic
1 pythonbasic1 pythonbasic
1 pythonbasic
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
PHP 101
PHP 101 PHP 101
PHP 101
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
 
Analytics functions in mysql, oracle and hive
Analytics functions in mysql, oracle and hiveAnalytics functions in mysql, oracle and hive
Analytics functions in mysql, oracle and hive
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cython
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
Lecture5 my sql statements by okello erick
Lecture5 my sql statements by okello erickLecture5 my sql statements by okello erick
Lecture5 my sql statements by okello erick
 

Similar a Closures

Problem 1 Show the comparison of runtime of linear search and binar.pdf
Problem 1 Show the comparison of runtime of linear search and binar.pdfProblem 1 Show the comparison of runtime of linear search and binar.pdf
Problem 1 Show the comparison of runtime of linear search and binar.pdfebrahimbadushata00
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
Swift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfSwift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfJkPoppy
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfRahul04August
 
Write a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdfWrite a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdfarri2009av
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingSergey Shishkin
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdffreddysarabia1
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetJose Perez
 
Arrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com ArrowArrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com ArrowLeandro Ferreira
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About RubyIan Bishop
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)riue
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語ikdysfm
 
Write a program that will test a name) method no sorting routine from.docx
 Write a program that will test a name) method no sorting routine from.docx Write a program that will test a name) method no sorting routine from.docx
Write a program that will test a name) method no sorting routine from.docxajoy21
 
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdfHi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdfanujsharmaanuj14
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collectionsMyeongin Woo
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3Abdul Haseeb
 
The Ring programming language version 1.10 book - Part 31 of 212
The Ring programming language version 1.10 book - Part 31 of 212The Ring programming language version 1.10 book - Part 31 of 212
The Ring programming language version 1.10 book - Part 31 of 212Mahmoud Samir Fayed
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!priort
 

Similar a Closures (20)

Problem 1 Show the comparison of runtime of linear search and binar.pdf
Problem 1 Show the comparison of runtime of linear search and binar.pdfProblem 1 Show the comparison of runtime of linear search and binar.pdf
Problem 1 Show the comparison of runtime of linear search and binar.pdf
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Swift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfSwift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdf
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
 
Write a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdfWrite a program that obtains the execution time of selection sort, bu.pdf
Write a program that obtains the execution time of selection sort, bu.pdf
 
Parameters
ParametersParameters
Parameters
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional Programming
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
Arrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com ArrowArrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com Arrow
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About Ruby
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
Write a program that will test a name) method no sorting routine from.docx
 Write a program that will test a name) method no sorting routine from.docx Write a program that will test a name) method no sorting routine from.docx
Write a program that will test a name) method no sorting routine from.docx
 
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdfHi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
The Ring programming language version 1.10 book - Part 31 of 212
The Ring programming language version 1.10 book - Part 31 of 212The Ring programming language version 1.10 book - Part 31 of 212
The Ring programming language version 1.10 book - Part 31 of 212
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
 

Más de SV.CO

Handout level-1-module-1
Handout   level-1-module-1Handout   level-1-module-1
Handout level-1-module-1SV.CO
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And DocumentsSV.CO
 
Building complex input screens
Building complex input screensBuilding complex input screens
Building complex input screensSV.CO
 
Working with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSONWorking with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSONSV.CO
 
Saving Data
Saving DataSaving Data
Saving DataSV.CO
 
Alerts notification
Alerts notificationAlerts notification
Alerts notificationSV.CO
 
UI Dynamics
UI DynamicsUI Dynamics
UI DynamicsSV.CO
 
Practical animation
Practical animationPractical animation
Practical animationSV.CO
 
Segues and navigation controllers
Segues and navigation controllersSegues and navigation controllers
Segues and navigation controllersSV.CO
 
Camera And Email
Camera And EmailCamera And Email
Camera And EmailSV.CO
 
Scroll views
Scroll viewsScroll views
Scroll viewsSV.CO
 
Intermediate table views
Intermediate table viewsIntermediate table views
Intermediate table viewsSV.CO
 
Table views
Table viewsTable views
Table viewsSV.CO
 
Protocols
ProtocolsProtocols
ProtocolsSV.CO
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycleSV.CO
 
Extensions
ExtensionsExtensions
ExtensionsSV.CO
 
Gestures
GesturesGestures
GesturesSV.CO
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycleSV.CO
 
Controls in action
Controls in actionControls in action
Controls in actionSV.CO
 
Auto layout and stack views
Auto layout and stack viewsAuto layout and stack views
Auto layout and stack viewsSV.CO
 

Más de SV.CO (20)

Handout level-1-module-1
Handout   level-1-module-1Handout   level-1-module-1
Handout level-1-module-1
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And Documents
 
Building complex input screens
Building complex input screensBuilding complex input screens
Building complex input screens
 
Working with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSONWorking with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSON
 
Saving Data
Saving DataSaving Data
Saving Data
 
Alerts notification
Alerts notificationAlerts notification
Alerts notification
 
UI Dynamics
UI DynamicsUI Dynamics
UI Dynamics
 
Practical animation
Practical animationPractical animation
Practical animation
 
Segues and navigation controllers
Segues and navigation controllersSegues and navigation controllers
Segues and navigation controllers
 
Camera And Email
Camera And EmailCamera And Email
Camera And Email
 
Scroll views
Scroll viewsScroll views
Scroll views
 
Intermediate table views
Intermediate table viewsIntermediate table views
Intermediate table views
 
Table views
Table viewsTable views
Table views
 
Protocols
ProtocolsProtocols
Protocols
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycle
 
Extensions
ExtensionsExtensions
Extensions
 
Gestures
GesturesGestures
Gestures
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycle
 
Controls in action
Controls in actionControls in action
Controls in action
 
Auto layout and stack views
Auto layout and stack viewsAuto layout and stack views
Auto layout and stack views
 

Último

Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 

Último (20)

Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 

Closures

  • 2. Closures let sortedTracks = tracks.sorted ( ) (firstTrack: Track, secondTrack: Track) -> Bool in return firstTrack.trackNumber < secondTrack.trackNumber
  • 3. Syntax func sum(numbers: [Int]) -> Int { // Code that adds together the numbers array return total } let sumClosure = { (numbers: [Int]) -> Int in // Code that adds together the numbers array return total }
  • 4. // A closure with no parameters and no return value let printClosure = { () -> Void in print("This closure does not take any parameters and does not return a value.") }
 // A closure with parameters and no return value let printClosure = { (string: String) -> Void in print(string) } // A closure with no parameters and a return value let randomNumberClosure = { () -> Int in // Code that returns a random number } // A closure with parameters and a return value let randomNumberClosure = { (minValue: Int, maxValue: Int) -> Int in // Code that returns a random number between `minValue` and `maxValue` }
  • 5. Passing closures as arguments let sortedTracks = tracks.sorted { (firstTrack: Track, secondTrack: Track) -> Bool in return firstTrack.trackNumber < secondTrack.trackNumber } let sortedTracks = tracks.sorted { (firstTrack: Track, secondTrack: Track) -> Bool in return firstTrack.starRating < secondTrack.starRating }
  • 6. Syntactic sugar let sortedTracks = tracks.sorted { (firstTrack: Track, secondTrack: Track) -> Bool in return firstTrack.starRating < secondTrack.starRating }
  • 7. Syntactic sugar let sortedTracks = tracks.sorted { (firstTrack, secondTrack) -> Bool in return firstTrack.starRating < secondTrack.starRating }
  • 8. Syntactic sugar let sortedTracks = tracks.sorted { (firstTrack, secondTrack) in return firstTrack.starRating < secondTrack.starRating }
  • 9. Syntactic sugar let sortedTracks = tracks.sorted { return $0.starRating < $1.starRating }
  • 10. Syntactic sugar let sortedTracks = tracks.sorted { $0.starRating < $1.starRating }
  • 11. Collection functions using closures Map Filter Reduce
  • 12. Collection functions using closures // Initial array let firstNames = ["Johnny", "Nellie", "Aaron", "Rachel"] // Creates an empty array that will be used // to store the full names var fullNames: [String] = [] for name in firstNames { let fullName = name + " Smith" fullNames.append(fullName) } 0 "Johnny Smith" 1 "Nellie Smith" 2 "Aaron Smith" 3 "Rachel Smith" fullNames
  • 13. Collection functions using closures // Initial array let firstNames = ["Johnny", "Nellie", "Aaron", "Rachel"] // Creates a new array of full names by adding "Smith" // to each first name let fullNames = firstNames.map { (name) -> String in return name + " Smith" } 0 "Johnny Smith" 1 "Nellie Smith" 2 "Aaron Smith" 3 "Rachel Smith" fullNames
  • 14. Collection functions using closures // Initial array let firstNames = ["Johnny", "Nellie", "Aaron", "Rachel"] // Creates a new array of full names by adding "Smith" // to each first name let fullNames = firstNames.map{ $0 + " Smith" } 0 "Johnny Smith" 1 "Nellie Smith" 2 "Aaron Smith" 3 "Rachel Smith" fullNames
  • 15. Collection functions using closures let numbers = [4, 8, 15, 16, 23, 42] var numbersLessThan20: [Int] = [] for number in numbers { if number < 20 { numbersLessThan20.append(number) } } 0 4 1 8 2 15 3 16 numbersLessThan20
  • 16. Collection functions using closures let numbers = [4, 8, 15, 16, 23, 42] let numbersLessThan20 = numbers.filter { (number) -> Bool in return number < 20 } 0 4 1 8 2 15 3 16 numbersLessThan20
  • 17. Collection functions using closures let numbers = [4, 8, 15, 16, 23, 42] let numbersLessThan20 = numbers.filter{ $0 < 20 } 0 4 1 8 2 15 3 16 numbersLessThan20
  • 18. Collection functions using closures let numbers = [8, 6, 7, 5, 3, 0, 9] var total = 0 for number in numbers { total = total + number }
  • 19. Collection functions using closures let numbers = [8, 6, 7, 5, 3, 0, 9] let total = numbers.reduce(0) { (currentTotal, newValue) -> Int in return currentTotal + newValue }
  • 20. Collection functions using closures let numbers = [8, 6, 7, 5, 3, 0, 9] let total = numbers.reduce(0,{ $0 + $1})
  • 21. Closures capture their environment animate { self.view.backgroundColor = .red }
  • 22. Lab: Closures Unit 5—Lesson 1 Open and complete the exercises in Lab - Closures.playground
  • 23. © 2017 Apple Inc. This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.