Skip to content

Latest commit

 

History

History
119 lines (88 loc) · 2.97 KB

File metadata and controls

119 lines (88 loc) · 2.97 KB

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.

protocol EastAsianable {
  var useChopstics: Bool { get }
  var origin: String { get }
}

Extend Protocol

Create an extension to EastAsianable that sets useChopstic as true

extension EastAsianable {
  // Extension may not contain stored properties
  var useChopstics: Bool {
    return true
  }
}

Create Blueprints

Create structs of Korean, Japanese, and Chinese that conform to EastAsianable.

struct Korean: EastAsianable {
  var origin: String = "Korea"
}


class Japanese: EastAsianable {
  var origin: String = "Japan"
}

struct Chinese: EastAsianable {
  var origin: String = "China"
}

Protocol as Type

you may group elements that conform to the EastAsianable protocol.

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.

for eastAsian in eastAsians {
  print("I'm from \(eastAsian.origin)")
}

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.

protocol Sleekable {
 var price: String { get }
}

Create Diamond, Ruby, and Glass that conform to Sleekable.

struct Diamond: Sleekable {
var price: String = "Very High"
}

struct Ruby: Sleekable {
var price: String = "High"
}

class Glass: Sleekable {
var price: String = "Dirt Cheap"
}

Create a generic function that only takes a parameter whose type must conform to Sleekable.

func stateThePrice<T: Sleekable>(enterGem: T) {
  print("I'm expensive. In fact, I'm \(enterGem.price)")
}

The stateThePrice function only accepts objects that conform to Sleekable.

stateThePrice(enterGem: Ruby())
// "I'm expensive. In fact, I'm Dirt Cheap"

Source Code

4003_protocol_type.playground

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.