Extending functionality with extensions
Extensions let us add functionalities to the existing classes, structs, enums, and protocols. This can be especially useful when the original type is provided by an external framework, and therefore you aren't able to add a functionality directly.
Getting ready
Imagine that we often need to obtain the first word from a given string. Rather than repeatedly writing the code to split the string into words and then retrieving the first word, we can extend the functionality of String
to provide its own first word.
How to do it...
Let's extend the functionality of String
, and then we will examine how it works:
- Add the following code to the playground:
extension String { func firstWord() -> String { let firstSpace = characters.index(of: " ") ?? characters.endIndex let firstName = String(characters.prefix(upTo: firstSpace)) return firstName } }
- Now we can use this new method on
String
to get the first word from a phrase:
let...