SlideShare una empresa de Scribd logo
1 de 28
Descargar para leer sin conexión
Unit 4—Lesson 1:
Protocols
Protocols
Defines a blueprint of methods, properties, and other requirements that suit a
particular task or piece of functionality

Swift standard library defines many protocols, including these:

•
CustomStringConvertible

•
Equatable

•
Comparable
•
Codable
•
When you adopt a protocol, you must implement all required methods.
Printing with CustomStringConvertible
let string = "Hello, world!"
print(string)
let number = 42
print(number)
let boolean = false
print(boolean)
Hello, world!
42
false
Printing with CustomStringConvertible
class Shoe {
let color: String
let size: Int
let hasLaces: Bool
init(color: String, size: Int, hasLaces: Bool) {
self.color = color
self.size = size
self.hasLaces = hasLaces
}
}
let myShoe = Shoe(color: "Black", size: 12, hasLaces: true)
print(myShoe)
__lldb_expr_1.Shoe
class Shoe: CustomStringConvertible {
let color: String
let size: Int
let hasLaces: Bool
init(color: String, size: Int, hasLaces: Bool) {
self.color = color
self.size = size
self.hasLaces = hasLaces
}
}
class Shoe: CustomStringConvertible {
let color: String
let size: Int
let hasLaces: Bool
init(color: String, size: Int, hasLaces: Bool) {
self.color = color
self.size = size
self.hasLaces = hasLaces
}
var description: String {
return "Shoe(color: (color), size: (size), hasLaces: (hasLaces))"
}
}
let myShoe = Shoe(color: "Black", size: 12, hasLaces: true)
print(myShoe)
Shoe(color: Black, size: 12, hasLaces: true)
Comparing information with Equatable
struct Employee {
let firstName: String
let lastName: String
let jobTitle: String
let phoneNumber: String
}
struct Company {
let name: String
let employees: [Employee]
}
Comparing information with Equatable
let currentEmployee = Session.currentEmployee
let selectedEmployee = Employee(firstName: "Jacob", lastName: "Edwards", 

jobTitle: "Marketing Director", phoneNumber: "415-555-9293")
if currentEmployee == selectedEmployee {
// Enable "Edit" button
}
Comparing information with Equatable
struct Employee: Equatable {
let firstName: String
let lastName: String
let jobTitle: String
let phoneNumber: String
static func ==(lhs: Employee, rhs: Employee) -> Bool {
// Logic that determines if the value on the left hand side and right hand side are equal
}
}
Comparing information with Equatable
struct Employee: Equatable {
let firstName: String
let lastName: String
let jobTitle: String
let phoneNumber: String
static func ==(lhs: Employee, rhs: Employee) -> Bool {
return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName
}
}
Comparing information with Equatable
let currentEmployee = Employee(firstName: "Jacob", lastName: "Edwards",
jobTitle: "Industrial Designer", phoneNumber: "415-555-7766")
let selectedEmployee = Employee(firstName: "Jacob", lastName: "Edwards",
jobTitle: "Marketing Director", phoneNumber: "415-555-9293")
if currentEmployee == selectedEmployee {
// Enable "Edit" button
}
Comparing information with Equatable
struct Employee: Equatable {
let firstName: String
let lastName: String
let jobTitle: String
let phoneNumber: String
static func ==(lhs: Employee, rhs: Employee) -> Bool {
return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName 

&& lhs.jobTitle == rhs.jobTitle && lhs.phoneNumber == rhs.phoneNumber
}
}
Sorting information with Comparable
let employee1 = Employee(firstName: "Ben", lastName: "Atkins", jobTitle: "Front Desk",
phoneNumber: "415-555-7767")
let employee2 = Employee(firstName: "Vera", lastName: "Carr", jobTitle: "CEO", phoneNumber:
"415-555-7768")
let employee3 = Employee(firstName: "Grant", lastName: "Phelps", jobTitle: "Senior Manager",
phoneNumber: "415-555-7770")
let employee4 = Employee(firstName: "Sang", lastName: "Han", jobTitle: "Accountant",
phoneNumber: "415-555-7771")
let employee5 = Employee(firstName: "Daren", lastName: "Estrada", jobTitle: "Sales Lead",
phoneNumber: "415-555-7772")
let employees = [employee1, employee2, employee3, employee4, employee5]
struct Employee: Equatable, Comparable {
let firstName: String
let lastName: String
let jobTitle: String
let phoneNumber: String
static func ==(lhs: Employee, rhs: Employee) -> Bool {
return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName
&& lhs.jobTitle == rhs.jobTitle && lhs.phoneNumber == rhs.phoneNumber
}
static func < (lhs: Employee, rhs: Employee) -> Bool {
return lhs.lastName < rhs.lastName
}
}
let employees = [employee1, employee2, employee3, employee4, employee5]
let sortedEmployees = employees.sorted(by:<)
for employee in sortedEmployees {
print(employee)
}
Employee(firstName: "Ben", lastName: "Atkins", jobTitle: "Front Desk", phoneNumber: "415-555-7767")
Employee(firstName: "Vera", lastName: "Carr", jobTitle: "CEO", phoneNumber: "415-555-7768")
Employee(firstName: "Daren", lastName: "Estrada", jobTitle: "Sales Lead", phoneNumber: "415-555-7772")
Employee(firstName: "Sang", lastName: "Han", jobTitle: "Accountant", phoneNumber: "415-555-7771")
Employee(firstName: "Grant", lastName: "Phelps", jobTitle: "Senior Manager", phoneNumber: "415-555-7770")
let employees = [employee1, employee2, employee3, employee4, employee5]
let sortedEmployees = employees.sorted(by:>)
for employee in sortedEmployees {
print(employee)
}
Employee(firstName: "Grant", lastName: "Phelps", jobTitle: "Senior Manager", phoneNumber: "415-555-7770")
Employee(firstName: "Sang", lastName: "Han", jobTitle: "Accountant", phoneNumber: "415-555-7771")
Employee(firstName: "Daren", lastName: "Estrada", jobTitle: "Sales Lead", phoneNumber: "415-555-7772")
Employee(firstName: "Vera", lastName: "Carr", jobTitle: "CEO", phoneNumber: "415-555-7768")
Employee(firstName: "Ben", lastName: "Atkins", jobTitle: "Front Desk", phoneNumber: "415-555-7767")
Encoding and decoding objects with Codable
struct Employee: Equatable, Comparable, Codable {
var firstName: String
var lastName: String
var jobTitle: String
var phoneNumber: String
static func ==(lhs: Employee, rhs: Employee) -> Bool {
return lhs.firstName == rhs.firstName && lhs.lastName ==
rhs.lastName && lhs.jobTitle == rhs.jobTitle &&
lhs.phoneNumber == rhs.phoneNumber
}
static func < (lhs: Employee, rhs: Employee) -> Bool {
return lhs.lastName < rhs.lastName
}
}
Encoding and decoding objects with Codable
let ben = Employee(firstName: "Ben", lastName: "Atkins", jobTitle: "Front Desk",
phoneNumber: "415-555-7767")
let jsonEncoder = JSONEncoder()
if let jsonData = try? jsonEncoder.encode(ben),
let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
{"firstName":"Ben","lastName":"Atkins","jobTitle":"Front Desk","phoneNumber":"415-555-7767"}
Creating a protocol
protocol FullyNamed {
var fullName: String { get }
func sayFullName()
}
struct Person: FullyNamed {
var firstName: String
var lastName: String
}
Creating a protocol
struct Person: FullyNamed {
var firstName: String
var lastName: String
var fullName: String {
return "(firstName) (lastName)"
}
func sayFullName() {
print(fullName)
}
}
Delegation
Enables a class or structure to hand off responsibilities to an instance of another
type

protocol ButtonDelegate {
func userTappedButton(_ button: Button)
}
class GameController: ButtonDelegate {
func userTappedButton(_ button: Button) {
print("User tapped the (button.title) button.")
}
}
GameController example (continued)
Delegation
class Button {
let title: String
var delegate: ButtonDelegate? // Add a delegate property to the Button
init(title: String) {
self.title = title
}
func tapped() {
self.delegate?.userTappedButton(self) // If the delegate exists, call the delegate
// function `userTappedButton` on the delegate
}
}
GameController example (continued)
Delegation
let startButton = Button(title: "Start Game")
let gameController = GameController()
startButton.delegate = gameController
startButton.tapped()
class Button {
let title: String
var delegate: ButtonDelegate? // Add a delegate property to the Button
init(title: String) {
self.title = title
}
func tapped() {
self.delegate?.userTappedButton(self) // If the delegate exists, call the delegate
// function `userTappedButton` on the delegate
}
}
class GameController: ButtonDelegate {
func userTappedButton(_ button: Button) {
print("User tapped the (button.title) button.")
}
}
MusicController example
Delegation
let musicController = MusicController()
let startMusicButton = Button(title: "Play")
startMusicButton.delegate = musicController
let stopMusicButton = Button(title: "Pause")
stopMusicButton.delegate = musicController
class MusicController: ButtonDelegate {
func playSong(_ song: Song) {
print("Now playing (song.title)")
}
func pauseSong() {
print("Paused current song.")
}
func userTappedButton(_ button: Button) {
if button.title == "Play" {
playSong(Playlist.songs.first)
} else if button.title == "Stop" {
pauseSong()
}
}
}
Lab: Protocols
Unit 4—Lesson 1
Open and complete the exercises in Lab - Protocols.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

Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data typeMegha V
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplAnkur Shrivastava
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in SwiftSeongGyu Jo
 
Python PCEP Function Parameters
Python PCEP Function ParametersPython PCEP Function Parameters
Python PCEP Function ParametersIHTMINSTITUTE
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overviewAveic
 
Json and SQL DB serialization Introduction with Play! and Slick
Json and SQL DB serialization Introduction with Play! and SlickJson and SQL DB serialization Introduction with Play! and Slick
Json and SQL DB serialization Introduction with Play! and SlickStephen Kemmerling
 
Favouring Composition - The Groovy Way
Favouring Composition - The Groovy WayFavouring Composition - The Groovy Way
Favouring Composition - The Groovy WayNaresha K
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwoEishay Smith
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Lucas Witold Adamus
 
Basic Object Oriented Concepts
Basic Object Oriented ConceptsBasic Object Oriented Concepts
Basic Object Oriented ConceptsScott Lee
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional ProgrammingDmitry Buzdin
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetSamuel Lampa
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionarySoba Arjun
 

La actualidad más candente (20)

Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data type
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in Swift
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Python PCEP Function Parameters
Python PCEP Function ParametersPython PCEP Function Parameters
Python PCEP Function Parameters
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overview
 
Json and SQL DB serialization Introduction with Play! and Slick
Json and SQL DB serialization Introduction with Play! and SlickJson and SQL DB serialization Introduction with Play! and Slick
Json and SQL DB serialization Introduction with Play! and Slick
 
Favouring Composition - The Groovy Way
Favouring Composition - The Groovy WayFavouring Composition - The Groovy Way
Favouring Composition - The Groovy Way
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?
 
Computer Science Homework Help
Computer Science Homework HelpComputer Science Homework Help
Computer Science Homework Help
 
Pytho dictionaries
Pytho dictionaries Pytho dictionaries
Pytho dictionaries
 
Basic Object Oriented Concepts
Basic Object Oriented ConceptsBasic Object Oriented Concepts
Basic Object Oriented Concepts
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
 
Python Regular Expressions
Python Regular ExpressionsPython Regular Expressions
Python Regular Expressions
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat Sheet
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 

Similar a Protocols

Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
The Ring programming language version 1.7 book - Part 25 of 196
The Ring programming language version 1.7 book - Part 25 of 196The Ring programming language version 1.7 book - Part 25 of 196
The Ring programming language version 1.7 book - Part 25 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 34 of 185
The Ring programming language version 1.5.4 book - Part 34 of 185The Ring programming language version 1.5.4 book - Part 34 of 185
The Ring programming language version 1.5.4 book - Part 34 of 185Mahmoud Samir Fayed
 
Madrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovyMadrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovyIván López Martín
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionHans Höchtl
 
The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210Mahmoud Samir Fayed
 

Similar a Protocols (20)

Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Python basic
Python basicPython basic
Python basic
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
The Ring programming language version 1.7 book - Part 25 of 196
The Ring programming language version 1.7 book - Part 25 of 196The Ring programming language version 1.7 book - Part 25 of 196
The Ring programming language version 1.7 book - Part 25 of 196
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
The Ring programming language version 1.5.4 book - Part 34 of 185
The Ring programming language version 1.5.4 book - Part 34 of 185The Ring programming language version 1.5.4 book - Part 34 of 185
The Ring programming language version 1.5.4 book - Part 34 of 185
 
Madrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovyMadrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovy
 
Python
PythonPython
Python
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181
 
The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210
 

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
 
Closures
ClosuresClosures
ClosuresSV.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
 
Closures
ClosuresClosures
Closures
 
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

How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
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
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
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
 
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
 
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
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
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
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 

Último (20)

Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
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...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
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...
 
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.
 
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
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
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
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 

Protocols

  • 2. Protocols Defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality Swift standard library defines many protocols, including these: • CustomStringConvertible • Equatable • Comparable • Codable • When you adopt a protocol, you must implement all required methods.
  • 3. Printing with CustomStringConvertible let string = "Hello, world!" print(string) let number = 42 print(number) let boolean = false print(boolean) Hello, world! 42 false
  • 4. Printing with CustomStringConvertible class Shoe { let color: String let size: Int let hasLaces: Bool init(color: String, size: Int, hasLaces: Bool) { self.color = color self.size = size self.hasLaces = hasLaces } } let myShoe = Shoe(color: "Black", size: 12, hasLaces: true) print(myShoe) __lldb_expr_1.Shoe
  • 5. class Shoe: CustomStringConvertible { let color: String let size: Int let hasLaces: Bool init(color: String, size: Int, hasLaces: Bool) { self.color = color self.size = size self.hasLaces = hasLaces } }
  • 6. class Shoe: CustomStringConvertible { let color: String let size: Int let hasLaces: Bool init(color: String, size: Int, hasLaces: Bool) { self.color = color self.size = size self.hasLaces = hasLaces } var description: String { return "Shoe(color: (color), size: (size), hasLaces: (hasLaces))" } } let myShoe = Shoe(color: "Black", size: 12, hasLaces: true) print(myShoe) Shoe(color: Black, size: 12, hasLaces: true)
  • 7. Comparing information with Equatable struct Employee { let firstName: String let lastName: String let jobTitle: String let phoneNumber: String } struct Company { let name: String let employees: [Employee] }
  • 8. Comparing information with Equatable let currentEmployee = Session.currentEmployee let selectedEmployee = Employee(firstName: "Jacob", lastName: "Edwards", 
 jobTitle: "Marketing Director", phoneNumber: "415-555-9293") if currentEmployee == selectedEmployee { // Enable "Edit" button }
  • 9. Comparing information with Equatable struct Employee: Equatable { let firstName: String let lastName: String let jobTitle: String let phoneNumber: String static func ==(lhs: Employee, rhs: Employee) -> Bool { // Logic that determines if the value on the left hand side and right hand side are equal } }
  • 10. Comparing information with Equatable struct Employee: Equatable { let firstName: String let lastName: String let jobTitle: String let phoneNumber: String static func ==(lhs: Employee, rhs: Employee) -> Bool { return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName } }
  • 11. Comparing information with Equatable let currentEmployee = Employee(firstName: "Jacob", lastName: "Edwards", jobTitle: "Industrial Designer", phoneNumber: "415-555-7766") let selectedEmployee = Employee(firstName: "Jacob", lastName: "Edwards", jobTitle: "Marketing Director", phoneNumber: "415-555-9293") if currentEmployee == selectedEmployee { // Enable "Edit" button }
  • 12. Comparing information with Equatable struct Employee: Equatable { let firstName: String let lastName: String let jobTitle: String let phoneNumber: String static func ==(lhs: Employee, rhs: Employee) -> Bool { return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName 
 && lhs.jobTitle == rhs.jobTitle && lhs.phoneNumber == rhs.phoneNumber } }
  • 13. Sorting information with Comparable let employee1 = Employee(firstName: "Ben", lastName: "Atkins", jobTitle: "Front Desk", phoneNumber: "415-555-7767") let employee2 = Employee(firstName: "Vera", lastName: "Carr", jobTitle: "CEO", phoneNumber: "415-555-7768") let employee3 = Employee(firstName: "Grant", lastName: "Phelps", jobTitle: "Senior Manager", phoneNumber: "415-555-7770") let employee4 = Employee(firstName: "Sang", lastName: "Han", jobTitle: "Accountant", phoneNumber: "415-555-7771") let employee5 = Employee(firstName: "Daren", lastName: "Estrada", jobTitle: "Sales Lead", phoneNumber: "415-555-7772") let employees = [employee1, employee2, employee3, employee4, employee5]
  • 14. struct Employee: Equatable, Comparable { let firstName: String let lastName: String let jobTitle: String let phoneNumber: String static func ==(lhs: Employee, rhs: Employee) -> Bool { return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName && lhs.jobTitle == rhs.jobTitle && lhs.phoneNumber == rhs.phoneNumber } static func < (lhs: Employee, rhs: Employee) -> Bool { return lhs.lastName < rhs.lastName } }
  • 15. let employees = [employee1, employee2, employee3, employee4, employee5] let sortedEmployees = employees.sorted(by:<) for employee in sortedEmployees { print(employee) } Employee(firstName: "Ben", lastName: "Atkins", jobTitle: "Front Desk", phoneNumber: "415-555-7767") Employee(firstName: "Vera", lastName: "Carr", jobTitle: "CEO", phoneNumber: "415-555-7768") Employee(firstName: "Daren", lastName: "Estrada", jobTitle: "Sales Lead", phoneNumber: "415-555-7772") Employee(firstName: "Sang", lastName: "Han", jobTitle: "Accountant", phoneNumber: "415-555-7771") Employee(firstName: "Grant", lastName: "Phelps", jobTitle: "Senior Manager", phoneNumber: "415-555-7770")
  • 16. let employees = [employee1, employee2, employee3, employee4, employee5] let sortedEmployees = employees.sorted(by:>) for employee in sortedEmployees { print(employee) } Employee(firstName: "Grant", lastName: "Phelps", jobTitle: "Senior Manager", phoneNumber: "415-555-7770") Employee(firstName: "Sang", lastName: "Han", jobTitle: "Accountant", phoneNumber: "415-555-7771") Employee(firstName: "Daren", lastName: "Estrada", jobTitle: "Sales Lead", phoneNumber: "415-555-7772") Employee(firstName: "Vera", lastName: "Carr", jobTitle: "CEO", phoneNumber: "415-555-7768") Employee(firstName: "Ben", lastName: "Atkins", jobTitle: "Front Desk", phoneNumber: "415-555-7767")
  • 17. Encoding and decoding objects with Codable struct Employee: Equatable, Comparable, Codable { var firstName: String var lastName: String var jobTitle: String var phoneNumber: String static func ==(lhs: Employee, rhs: Employee) -> Bool { return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName && lhs.jobTitle == rhs.jobTitle && lhs.phoneNumber == rhs.phoneNumber } static func < (lhs: Employee, rhs: Employee) -> Bool { return lhs.lastName < rhs.lastName } }
  • 18. Encoding and decoding objects with Codable let ben = Employee(firstName: "Ben", lastName: "Atkins", jobTitle: "Front Desk", phoneNumber: "415-555-7767") let jsonEncoder = JSONEncoder() if let jsonData = try? jsonEncoder.encode(ben), let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString) } {"firstName":"Ben","lastName":"Atkins","jobTitle":"Front Desk","phoneNumber":"415-555-7767"}
  • 19. Creating a protocol protocol FullyNamed { var fullName: String { get } func sayFullName() } struct Person: FullyNamed { var firstName: String var lastName: String }
  • 20. Creating a protocol struct Person: FullyNamed { var firstName: String var lastName: String var fullName: String { return "(firstName) (lastName)" } func sayFullName() { print(fullName) } }
  • 21. Delegation Enables a class or structure to hand off responsibilities to an instance of another type protocol ButtonDelegate { func userTappedButton(_ button: Button) } class GameController: ButtonDelegate { func userTappedButton(_ button: Button) { print("User tapped the (button.title) button.") } }
  • 22. GameController example (continued) Delegation class Button { let title: String var delegate: ButtonDelegate? // Add a delegate property to the Button init(title: String) { self.title = title } func tapped() { self.delegate?.userTappedButton(self) // If the delegate exists, call the delegate // function `userTappedButton` on the delegate } }
  • 23. GameController example (continued) Delegation let startButton = Button(title: "Start Game") let gameController = GameController() startButton.delegate = gameController startButton.tapped()
  • 24. class Button { let title: String var delegate: ButtonDelegate? // Add a delegate property to the Button init(title: String) { self.title = title } func tapped() { self.delegate?.userTappedButton(self) // If the delegate exists, call the delegate // function `userTappedButton` on the delegate } } class GameController: ButtonDelegate { func userTappedButton(_ button: Button) { print("User tapped the (button.title) button.") } }
  • 25. MusicController example Delegation let musicController = MusicController() let startMusicButton = Button(title: "Play") startMusicButton.delegate = musicController let stopMusicButton = Button(title: "Pause") stopMusicButton.delegate = musicController
  • 26. class MusicController: ButtonDelegate { func playSong(_ song: Song) { print("Now playing (song.title)") } func pauseSong() { print("Paused current song.") } func userTappedButton(_ button: Button) { if button.title == "Play" { playSong(Playlist.songs.first) } else if button.title == "Stop" { pauseSong() } } }
  • 27. Lab: Protocols Unit 4—Lesson 1 Open and complete the exercises in Lab - Protocols.playground
  • 28. © 2017 Apple Inc. This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.