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" ...

Get Swift Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.