Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Extensions


With extensions, we can add new properties, methods, initializers, subscripts, or make an existing type conform to a protocol. One thing to note is that extensions cannot override existing functionality.

To define an extension, we use the extension keyword followed by the type that we are extending. The following example shows how we would create an extension that extends the string class:

extension String {
  //add new functionality here
}

Let's see how extensions work by adding a reverse() method and a firstLetter property to Swift's standard string class:

extension String {
    var firstLetter: Character {
        get {
            var letters = Array(self)
            return letters[0]
        }
    }

    func reverse() -> String {
        var reverse = ""
        for letter in self {
            reverse = "\(letter)" + reverse
        }
        return reverse
    }
}

When we extend an existing class or structure we define properties, methods, initializers, subscripts, and...