Swift / Advanced Swift Concepts
Extension Creation
This tutorial will teach you how to create extensions in Swift. Extensions allow you to add new functionality to existing classes, structures, enumerations, or protocol types.
Section overview
4 resourcesCovers advanced Swift concepts like extensions, generics, and protocols.
1. Introduction
Goal
This tutorial aims to guide you through the process of creating extensions in Swift. Extensions are a powerful feature in Swift that allow you to add new functionality to existing classes, structures, enumerations, or protocol types.
Learning Outcomes
By the end of this tutorial, you will be able to:
- Understand the concept of extensions in Swift
- Create your own extensions
- Add computed properties and methods to existing types using extensions
Prerequisites
Before starting with this tutorial, you should have a basic understanding of Swift programming, including classes, structures, and enumerations.
2. Step-by-Step Guide
Extensions in Swift are a way to add functionality to existing types. This can include adding new methods or computed properties, or enabling existing types to adopt protocols.
2.1 Creating an Extension
Creating an extension in Swift is done using the extension keyword followed by the name of the type you want to extend. Inside the curly braces, you can add new functionality.
extension SomeType {
// new functionality to add to SomeType goes here
}
2.2 Adding Computed Properties
Extensions can add computed instance properties and computed type properties. Here is an example of adding a computed instance property to Swift's built-in Double type that returns the square of the value.
extension Double {
var squared: Double {
return self * self
}
}
let three = 3.0
print(three.squared) // Prints "9.0"
2.3 Adding Methods
Extensions can also add new methods to existing types. The following example adds a new method describe() to the Int type.
extension Int {
func describe() {
print("This is the number \(self)")
}
}
let number = 42
number.describe() // Prints "This is the number 42"
3. Code Examples
Example 1: Adding a Method to String Type
extension String {
func shout() -> String {
return self.uppercased() + "!!!"
}
}
let greeting = "hello"
print(greeting.shout()) // Prints "HELLO!!!"
In this example, we add a method shout() to the String type that returns the string in uppercase followed by three exclamation marks.
Example 2: Adding a Computed Property to Int Type
extension Int {
var isEven: Bool {
return self % 2 == 0
}
}
let number = 4
print(number.isEven) // Prints "true"
This example adds a computed property isEven to the Int type that returns true if the integer is even and false otherwise.
4. Summary
In this tutorial, we've learned how to create extensions in Swift and use them to add new functionality to existing types. We've seen how to add computed properties and methods to types.
For further learning, you can explore how to use extensions to enable a type to adopt a protocol, or add initializers to existing types.
5. Practice Exercises
Exercise 1: Extend the Double type with a cubed computed property that returns the cube of the value.
Solution:
extension Double {
var cubed: Double {
return self * self * self
}
}
let two = 2.0
print(two.cubed) // Prints "8.0"
Exercise 2: Extend the String type with a reverse method that returns the string in reverse order.
Solution:
extension String {
func reverse() -> String {
return String(self.reversed())
}
}
let greeting = "hello"
print(greeting.reverse()) // Prints "olleh"
Continue practicing by creating your own extensions and adding more complex functionality.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article