Variables and functions
suggest changeExtensions 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents