Extensions can contain functions and computed/constant get variables. They are in the format
extension ExtensionOf {
//new functions and get-variables
}
To reference the instance of the extended object, self
can be used, just as it could be used
To create an extension of String
that adds a .length()
function which returns the length of the string, for example
extension String {
func length() -> Int {
return self.characters.count
}
}
"Hello, World!".length() // 13
Extensions can also contain get
variables. For example, adding a .length
variable to the string which returns the length of the string
extension String {
var length: Int {
get {
return self.characters.count
}
}
}
"Hello, World!".length // 13