NEW! Master Swift design patterns with my latest book! >>

< Previous: Overview   Next: Creating a Swift extension >

Setting up

There's one technique I've been patiently waiting to show you since this series started, and now is the right time: extensions. Cunningly, this is not at all the same thing I already showed you in project 16, which was when we created an extension to Safari. This time we're going to create extensions for Swift – literally extending the language so it can do more things.

This isn't complicated – honest! We're not trying to make Swift do things it wasn't designed to do; in fact, I'd wager that language extensions are used in nearly all major projects that are shipping today. Why? Because they let you attach functionality to data types you didn't create. You've seen time and time again how we can add any methods we want to our own classes. Well, extensions let you do that to other classes and structs, including Apple's own.

There isn't enough in extensions to give you an intellectual challenge, so you're going to learn about extensions while using a Swift playground. We haven't used these yet because they haven't been appropriate, but now is a good chance. I'm also going to take this opportunity to outline in more detail the differences between functions and methods.

In Xcode, go to the File menu and choose New > Playground. Name it Project24, make sure iOS is selected as the platform, then choose Next and save it somewhere you can find later. Swift playgrounds are split into two columns: the left half contains your code, the right contains your output.

Download for free!

Want a free 75-minute video teaching functional programming, protocol-oriented programming, and more? This is your lucky day!

< Previous: Overview   Next: Creating a Swift extension >
MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>