Extension

Introduction

Welcome to Lesson 10 of The Swift Fundamentals. In this lesson, you will learn how to keep your codebase modularized and dry throughextension.

Problem

  1. I like to keep it short and modularized.
  2. Prevent anything massive.

Design Struct

First, design a struct called, Bob. It contains two initialized properties: name and skill.

  1. struct Bob {
  2. var name = "Bob"
  3. var skill = "Work"
  4. init() {}
  5. }

Extend Struct

You may “extend” the Bob struct and add all kinds of work.

  1. extension Bob {
  2. var description: String {
  3. let myName = self.name
  4. let mySkill = self.skill // object.name
  5. return "I'm \(name), I know \(skill)"
  6. }
  7. init(enterSkill: String) {
  8. self.skill = enterSkill
  9. print("You've entered a new skill")
  10. }
  11. subscript(mySkill: String) -> String {
  12. return "This is your secret weapon"
  13. }
  14. }

self refers to the object created by the struct. If you do not know how to work with computed properties, you may visit 2002_computed_property and come back after.

Check

Create an object called bob.

  1. let bob = Bob()
  2. bob.description // I'm Bob, I know work"

You may use init(enterSkill: String) from the extension block.

  1. let newBob = Bob(enterSkill: "Drawing")
  2. newBob.description // I'm Bob, I know drawing"

Extend Swift Native Types

Remember, Int just a struct

Instead of creating a separate function, you may extend Int and add a property.

  1. extension Int {
  2. var squared: Int {
  3. return self * self
  4. }
  5. }

Now, objects whose type is Int, contain the squared property.

  1. let myNumber = 10 // self is 10
  2. myNumber.squared // 100

The Rule

  • You may not have a stored property within extension.

The Scope

As mentioned, extension allows developers to implement all kinds of features.

Source Code

1010_extension.playground

Conclusion

You’ve learned the meaning of self. I use extension to modularize view controller to prevent MVC, a.k.a, Massive View Controller.

In Chapter 4, you will learn the sheer power of extension along with protocols If you are interested in learning how to build apps with Protocols and best practices that I know of, you may join the VIP list for the upcoming course: The UIKIt Fundamentals with Bob.