Swift and SwiftUI tutorials for Swift Developers

What is an Extension in Swift and how to use it

Another way to add new functionality to a Swift class is to use an extension. Extensions allow you to add features such as methods, initializers, computed properties, and subscripts to an existing class without having to create or reference a subclass. This is especially effective when using extensions to add functionality to built-in classes in the Swift programming language and iOS SDK frameworks.

To extend a class, use the following syntax:

extension ClassName {

	//code

}

As an example, suppose we need to add some additional properties to the standard Double class that will return the value raised to the power 2 and 3. This functionality can be added using the following extension declaration:

extension Double {

	var squared: Double {
		return self*self
	}

	var cubed: Double {
		return self*self*self
	}
}

After extending the Double class with two new computed properties, we can now use the properties as we would any other Double class, such as:

let myValue: Double = 3.0
print(myValue.squared)

When executed, the print statement will output the value 9.0. Note that by declaring the constant myValue, we were able to declare it as a Double and access the extension’s properties without needing to subclass it. In fact, since these properties were added as an extension, rather than using a subclass, we can now access them directly as Double values.

Extensions offer a quick and convenient way to extend a class’s functionality without needing to subclass it. However, subclasses still have some advantages over extensions. For example, it’s not possible to override a class’s existing functionality with an extension, and extensions can’t contain stored properties.

If you have any questions about this article, please contact me and I’ll be happy to help šŸ™‚ You can reach me on my X profile or on my Instagram profile.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Article

How to change the navigation bar title font color in SwiftUI

Next Article

Integrating MapKit with SwiftUI

Related Posts