Welcome to our Swift Extensions tutorial! In this lesson, we'll learn about one of Swift's most powerful features – Extensions. By the end of this tutorial, you'll be able to extend the functionality of existing Swift classes and types.
Extensions allow you to add new functionality to an existing Swift class, structure, enumeration, or protocol without subclassing. This means you can modify existing types without modifying their original source code.
Extensions are useful when you want to:
String, Int, and ArrayTo create an extension, simply write the extension keyword followed by the type you want to extend, and then add the new functionality between curly braces {}.
Here's a simple example of extending the String type to reverse its contents:
extension String {
func reversed() -> String {
return self.reversed()
}
}
let hello = "Hello, World!"
print(hello.reversed()) // Prints "!dlroW ,olleH"In this example, we've added a new method called reversed() to the String type. Now, every String instance can reverse its contents using this method.
Extensions can also inherit functionality from other extensions:
extension String {
func reversed() -> String {
return self.reversed()
}
}
extension String {
func capitalized() -> String {
return self.capitalized
}
}
let hello = "hello, world!"
print(hello.capitalized().reversed()) // Prints "WORLD!hllo"In this example, we've added two extensions to the String type: reversed() and capitalized(). We've also demonstrated how they can be combined to create more complex functionality.
Extensions can be used to make existing types conform to protocols:
protocol Printable {
func printDescription()
}
extension String: Printable {
func printDescription() {
print("This is a String: \(self)")
}
}
let hello = "Hello, World!"
hello.printDescription() // Prints "This is a String: Hello, World!"In this example, we've created a Printable protocol with a printDescription() method. We've then used an extension to make String conform to this protocol.
What does an extension do in Swift?
What are some benefits of using extensions in Swift?