Lesson 011 – Intro to Extensions

Extension CordBack in Lesson 006, we took a look at classes. Classes and Structs give us a lot of flexibility in making our program operate. They offer us a way to organize our data, organize application functionality, and make our program potentially easier to understand for those developers who come after us. As we discussed in that Lesson, Swift itself comes with lots of classes like String that we use frequently. However, what if you wanted to make the String class behave differently? Or what if you wanted to “add on” to String to make it do more for you?

Introducing Extensions

Swift has made it possible for you to change behavior of classes without changing the actual class itself. Let’s take a look at simple class that is supposed to represent a blog post.

Nothing crazy here, yet. This is how we dealt with classes back in Lesson 006. However, what if Post was shared between some applications and just for our project, we wanted Post to contain another property. What if we wanted that property to be a Post Heading that was computed by putting the Title and Author together? Enter the extension keyword.

First, we just use the keyword extension, then name the class we are extending. Then, inside the curly braces, we just add code like we were in the original class file. In my playground, I even declared this extension AFTER declaring my lesson001 variable and it still worked and printing the heading printed “Lesson 001 – Variables by Pete”. The code to this point looks like this and works as advertised.

Extending System Classes

We aren’t stuck just randomly extending our own classes. We can actually extend system classes for our own use, also. For instance, here I’ve added a method to the String class that will just return two copies of the string. Notice that I used the keyword self to refer to the String. You can do that because you are basically operating as if you were in the original class file when it was originally written.

Just because I’ve extended the class one time doesn’t mean that I’m done. I can actually open it up and extend it again. Also, don’t think that you have to only add one thing at a time. This time, I add two new properties to String and Swift doesn’t mind at all.


Swift Extensions allow us to extend the behavior of classes, both System and Custom Classes. You should use this ability sparingly, however. You will always have to take a dependency on the code files that create the extensions and this will be functionality that may not be readily apparent to new programmers who come after you to maintain your application. However, if you have good reason to extend the classes, Swift has your back 😉

The source code for this lesson and all lessons can be found on GitHub.

Add Comment

Required fields are marked *. Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.