Protocol as Type
Introduction
Welcome to Lesson 3 of Protocol Oriented Swift. In this lesson, you will learn how to group objects together through protocols.
Problem
No more type casting
Design Protocol
Create a protocol called, EastAsianable. It contains two properties.
1. protocol EastAsianable {
2. var useChopstics: Bool { get }
3. var origin: String { get }
4. }
Extend Protocol
Create an extension to EastAsianable that sets useChopstic as true
1. extension EastAsianable {
2. // Extension may not contain stored properties
3. var useChopstics: Bool {
4. return true
5. }
6. }
Create Blueprints
Create structs of Korean, Japanese, and Chinese that conform to EastAsianable.
1. struct Korean: EastAsianable {
2. var origin: String = "Korea"
3. }
6. class Japanese: EastAsianable {
7. var origin: String = "Japan"
8. }
10. struct Chinese: EastAsianable {
11. var origin: String = "China"
12. }
Protocol as Type
you may group elements that conform to the EastAsianable protocol.
1. let eastAsians: [EastAsianable] = [Korean(), Japanese(), Chinese()]
The type of the array is [EastAsianable].
Since every element that conforms to EastAsianable contains origin, you may loop through array.
1. for eastAsian in eastAsians {
2. print("I'm from \(eastAsian.origin)")
3. }
Practical Examples
You may combine UILabel, UIImageView, loop through to change colors, animation. Use your imagination.
Protocol Met Generics
Create a protocol called, Sleekable that contain a property.
1. protocol Sleekable {
2. var price: String { get }
3. }
Create Diamond, Ruby, and Glass that conform to Sleekable.
1. struct Diamond: Sleekable {
2. var price: String = "Very High"
3. }
5. struct Ruby: Sleekable {
6. var price: String = "High"
7. }
9. class Glass: Sleekable {
10. var price: String = "Dirt Cheap"
11. }
Create a generic function that only takes a parameter whose type must conform to Sleekable.
1. func stateThePrice<T: Sleekable>(enterGem: T) {
2. print("I'm expensive. In fact, I'm \(enterGem.price)")
3. }
The stateThePrice function only accepts objects that conform to Sleekable.
1. stateThePrice(enterGem: Ruby())
2. // "I'm expensive. In fact, I'm Dirt Cheap"
Source Code
Resources
Intro to Protocol Oriented Programming
Conclusion
You’ve learned how to combine objects created with structs and classes into a single array without type casting. It works because a protocol is used as a type. A true magic.
In the following lesson, you will learn how to pass data between classes using delegate.
Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.
