SlideShare a Scribd company logo
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.

More Related Content

What's hot

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
Megha V
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in Swift
SeongGyu Jo
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
Benjamin Waye
 
Python : Functions
Python : FunctionsPython : Functions
Python PCEP Function Parameters
Python PCEP Function ParametersPython PCEP Function Parameters
Python PCEP Function Parameters
IHTMINSTITUTE
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overview
Aveic
 
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 Way
Naresha K
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
Iran Entrepreneurship Association
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
Eishay 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
 
Computer Science Homework Help
Computer Science Homework HelpComputer Science Homework Help
Computer Science Homework Help
Programming Homework Help
 
Basic Object Oriented Concepts
Basic Object Oriented ConceptsBasic Object Oriented Concepts
Basic Object Oriented Concepts
Scott Lee
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional ProgrammingDmitry Buzdin
 
Python Regular Expressions
Python Regular ExpressionsPython Regular Expressions
Python Regular Expressions
BMS Institute of Technology and Management
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat Sheet
Samuel Lampa
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 

What's hot (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 to Protocols

Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
Arturo Herrero
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
Giordano 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 196
Mahmoud 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 185
Mahmoud 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 groovy
Iván López Martín
 
Python
PythonPython
Python
MeHak Gulati
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Hans 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 181
Mahmoud 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 210
Mahmoud Samir Fayed
 

Similar to 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
 

More from SV.CO

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

More from 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
 

Recently uploaded

678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 

Recently uploaded (20)

678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 

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.