Variables and functions

suggest change

Extensions can contain functions and computed properties, including read-only ones. They cannot contain stored properties. The form is

extension ExtensionOf {
    //new functions and get-variables
}

To reference the instance, use self, as in any method.

This extension adds a length() method:

extension String {
    func length() -> Int {
        return self.count
    }
}

"Hello, World!".length() // 13

Extensions can also contain computed properties. For example, a length property that returns the length of the string:

extension String {
    var length: Int {
        get {
            return self.count
        }
    }
}

"Hello, World!".length // 13

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents