Extensions
With extensions, we can add new properties, methods, initializers, and subscripts, or make an existing class or structure conform to a protocol without modifying the source code for the class or structure. One thing to note is that extensions cannot override the 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 { return self.characters.first } } func reverse() -> String { var reverse = "" for letter in self.characters { reverse = "\(letter)" + reverse...