Book Image

Application Development with Swift

By : Hossam Ghareeb
Book Image

Application Development with Swift

By: Hossam Ghareeb

Overview of this book

Table of Contents (14 chapters)

Extensions


Extensions are used to add new functionality to an existing class, enumeration, or structure. They are like categories in Objective-C, but in Swift we have two differences:

  • Extensions can be used with classes, enumerations, and structures

  • Extensions don't have names

In Swift, extensions can do many things. Check this list:

  • Add computed properties and computed type properties

  • Add instance methods and class methods

  • Define subscripts

  • Add new initializers

  • Make the existing type conform to protocol

To create an extension, use this form:

extension someType{
    //New functionalities go here
}

In extensions, as we said, you can add new functionalities, but you can't override an existing one.

Adding computed properties

Extensions can add computer instance properties and computed type properties in any existing type. Check the following example:

extension Double{
    
    var km : Double{
        return self / 1000.0;
    }
    var cm : Double{
        return self * 100.0
    }
}

var distance = 1500...