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
- I like to keep it short and modularized.
- 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"
5. init() {}
6. }
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. }
8. init(enterSkill: String) {
9. self.skill = enterSkill
10. print("You've entered a new skill")
11. }
13. subscript(mySkill: String) -> String {
14. return "This is your secret weapon"
15. }
16. }
selfrefers to the object created by the struct. If you do not know how to work withcomputed 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,
Intjust 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.
- Add computed instance properties and computed type properties (2002_computed_property)
- Define instance methods and type methods (2007_type_property_method)
- Provide new initializers
- Define subscripts (1007_subscripts)
- Define and use new nested types with enum/struct
- Make an existing type conform to a protocol
Source Code
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.
