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 Slick
Stephen 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
 
Pytho dictionaries
Pytho dictionaries Pytho dictionaries
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 Programming
Dmitry 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.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi 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
 
Scala introduction
Scala introductionScala introduction
Scala introduction
Alf Kristian Støyle
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
Norhisyam Dasuki
 
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

Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
Wahiba Chair Training & Consulting
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 

Recently uploaded (20)

Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 

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.