Learn iOS Development

Practical Examples of Swift Extensions

When and How to Use

Shashank Thakur
Level Up Coding
Published in
3 min readNov 8, 2023

--

Extensions in Swift
Photo by Karthik Sridasyam on Unsplash

Swift extensions are a versatile feature that allows you to extend the functionality of existing types, making your code more modular, readable, and organized. In this blog, we’ll explore practical examples of when and how to use Swift extensions, demonstrating their usefulness in real-world scenarios.

1. Adding Computed Properties

Swift extensions are an excellent way to add computed properties to existing types. Computed properties allow you to calculate values based on the existing properties of a type or even introduce entirely new properties.

Example: Extending String to calculate its length.

extension String {
var length: Int {
return count
}
}

let text = "Hello, Swift"
let textLength = text.length // 12

2. Implementing Protocol Conformance

Extensions can be used to make existing types conform to protocols. This is especially useful when you want to adapt types to specific requirements or when working with libraries that expect conforming types.

Example: Making Int conform to the CustomStringConvertible protocol.

extension Int: CustomStringConvertible {
public var description: String {
return "Number: \(self)"
}
}

let number = 42
print(number) // Number: 42

3. Providing Convenience Initializers

Extensions allow you to add convenience initializers to types. This is valuable when you need to create instances with specific configurations without cluttering the primary initializer.

Example: Extending UIColor to create colors from RGB values.

extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
self.init(
red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: 1.0
)
}
}

let customColor = UIColor(red: 100, green: 200, blue: 50)

4. Adding Methods

Extensions can add methods to types, providing new functionality that wasn’t originally part of the type’s definition.

Example: Extending Array to return the sum of its elements.

extension Array where Element: Numeric {
func sum() -> Element {
return reduce(0, +)
}
}

let numbers = [1, 2, 3, 4, 5]
let total = numbers.sum() // 15

5. Adding Subscripts

Extensions can add subscripts to types, providing indexed access to elements. Subscripts are a valuable way to offer more convenient access to specific elements within a type.

Example: Extending String to access characters by index.

extension String {
subscript(index: Int) -> Character {
let charIndex = self.index(self.startIndex, offsetBy: index)
return self[charIndex]
}
}

let text = "Swift"
let thirdCharacter = text[2] // "i"

6. Customizing UI Components

You can use extensions to add custom functionality to UIKit or SwiftUI components, making them more versatile for your app’s specific needs.

Example: Extending UIButton to add a rounded appearance.

extension UIButton {
func makeRounded() {
layer.cornerRadius = bounds.height / 2
clipsToBounds = true
}
}

let myButton = UIButton()
myButton.makeRounded()

7. Extending Third-party Libraries

Extensions also allow you to extend types from third-party libraries, adding functionality without modifying their source code.

Example: Extending a third-party Date type to format dates.

import ThirdPartyLibrary

extension ThirdPartyDate {
func formattedDate() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy"
return formatter.string(from: self)
}
}

let date = ThirdPartyDate()
let formatted = date.formattedDate()

Conclusion

Swift extensions are a powerful feature that can enhance the versatility and modularity of your code. By adding computed properties, implementing protocol conformance, providing convenience initializers, adding methods, introducing subscripts, customizing UI components, and extending third-party libraries, you can make your code more efficient and readable. Swift extensions enable you to adapt and enhance existing types to suit your specific needs, making your development process smoother and your codebase more maintainable.

--

--