- Recap on Protocols in Swift Standard Library
- Benefits using Protocols
- Extensions
- Pair-programming activity
By the end of this lesson, students should be able to:
- Work with extensions
- Use Protocols and Inheritance to build a character creation system
- Identify pros and limitations of protocols
let howManyTrees = Tree.allCases.count
//4
CaseIterable Protocol
let addresses = [StreetAddress("1490", "Grove Street"),
StreetAddress("2119", "Maple Avenue"),
StreetAddress("1400", "16th Street")]
let home = StreetAddress("1400", "16th Street")
print(addresses[0] == home)
Equatable Protocol
let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
if ingredients.contains("sugar") {
print("No thanks, too sweet.")
}
Hashable Protocol
let bugs = ["Ant", "Spider", "Mantis", "Fly", "Caterpillar"]
for bug in bugs {
print(bug)
}
Sequence Protocol
let text = "Hello, hello, hello again."
if let firstComma = text.firstIndex(of: ",") {
print(text[..<firstComma])
}
Collection Protocol
Given the Artist struct below, implement the Equatable protocol. You'll define what makes two instances equal.
// Used by Artist to determine style of Artist
enum Style: String {
case impressionism
case surrealism
case cubism
case popArt
}
struct Artist {
let name: String
let style: Style
let yearBorn: Int
}
// Example instances of Artists, use for testing your equatable
let monet = Artist(name: "Monet", style: .impressionism, yearBorn: 1840)
let dali = Artist(name: "Salvador Dali", style: .surrealism, yearBorn: 1904)
let andy = Artist(name: "Andy Warhol", style: .popArt, yearBorn: 1928)
//This is what we want to achieve, being able to compare artists like:
monet == dali //returns true? false?
What are some benefits you've seen so far about using protocols?
Behavior similar to multiple-inheritance
Adopted by classes, structs & enums
Value types = less risk
Extensions add new functionality to an existing class, structure, enumeration, or protocol type.
- Add computed properties
- Define methods
- Provide new initializers
- Make an existing type conform to a protocol
Protocols can be extended to provide methods, initializers, and computed property implementations to conforming types.
This allows us to define behavior on protocols themselves, rather than in each type’s individual conformance.
extension FullName {
func printUppercase(){
print(fullName.uppercased())
}
}
var me = Person(firstName: "Haruki", lastName: "Murakami")
me.printUppercase()
extension FullName {
func printToConsole(){
print(fullName)
}
}
var me = Person(firstName: "Haruki", lastName: "Murakami")
me.printToConsole()
How to know when to use a subclass and an extension?
What is a protocol in Swift?
What does it mean when a class conforms to a protocol?
Why is there a limitation when using OOP when it comes to inheritance?
How do protocols solve this limitation?
In pairs, go over the following activity where you'll use inheritance and protocols to build the characters of a game.