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.

Tutorial 2 of 4 4 resources in this section

Section overview

4 resources

Covers 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help