O'Reilly logo

Swift Quick Syntax Reference by Matthew Campbell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter    45

Extensions

You use extensions when you want to add methods and computed properties to a class, structure, or enumeration that already exists. This comes in handy when you want new behavior for a type but only in a particular context. Extensions will remind Objective-C programmers of categories.

To extend a type, you use the extension keyword followed by the name of the type you want to extend, as shown in Listing 45-1.

Listing 45-1. Extending the Person Class

class Person {    var name: String = "Name"    var age:Int = 0    func profile() -> String {        return "I'm \(self.name) and I'm \(self.age) years old."    }}extension Person {    var dogYears:Int {    get{        return self.age * 7    }    }}var p = Person()p.name = "Matt" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required