100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Swift

Extensions in Swift

Discover how Swift extensions add new functionality to existing types without modifying their original source code.

Protocols & GenericsIntermediate7 min readJul 8, 2026
Analogies

Introduction

An extension in Swift adds new functionality to an existing type, such as a class, struct, enum, or protocol, even if you do not have access to the original source code. Extensions can add computed properties, instance and type methods, initializers, subscripts, and protocol conformance. However, extensions cannot add stored properties or override existing functionality — they can only extend, not replace, what a type already does.

🏏

Cricket analogy: Adding a custom strikeRate computed property to Apple's built-in Int type via an extension is like a broadcaster overlaying a strike-rate graphic onto official scorecard data they don't own the source for, adding insight but not rewriting the underlying scorecard.

Syntax

swift
extension Int {
    func squared() -> Int {
        return self * self
    }
}

Explanation

The keyword extension is followed by the name of the type being extended, here Int, Swift's built-in integer type. Inside the braces, a new method squared() is defined that operates on self, the integer value the method is called on. Because Int is a type from the Swift standard library, extensions let you add behavior to it as if you had written it yourself, without subclassing or modifying the original type definition.

🏏

Cricket analogy: extension Int { func squared() -> Int { self * self } } is like adding a custom runsSquared() stat to the standard scoring system, where self refers to the specific score you called it on, without rewriting how scores are stored.

Example

swift
extension String {
    var isPalindrome: Bool {
        let cleaned = self.lowercased()
        return cleaned == String(cleaned.reversed())
    }
}

let word = "Level"
print(word.isPalindrome)

Output

swift
true

Key Takeaways

  • Extensions add new functionality to existing types, including ones you don't own like Int or String.
  • Extensions can add computed properties, methods, initializers, subscripts, and protocol conformance.
  • Extensions cannot add stored properties or override existing methods.
  • Extensions keep related functionality organized separately from the original type definition.
  • Extensions are commonly used to make a type conform to a protocol in a focused, readable block.

Practice what you learned

Was this page helpful?

Topics covered

#Swift#SwiftProgrammingStudyNotes#Programming#ExtensionsInSwift#Extensions#Syntax#Explanation#Example#StudyNotes#SkillVeris