Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Swift Dictionary

  1. Home
  2. Swift Dictionary
  3. extension Basics / Adding Methods

extension Basics / Adding Methods

The extension keyword lets you add methods, properties, and other members to an existing type — such as a class, struct, or enum — without modifying its original source code.

Syntax

extension TypeName {
    // Add methods, properties, initializers, etc.
    func methodName() -> ReturnType { }
    var propertyName: Type { return value }
}

Syntax overview

SyntaxDescription
extension TypeName { }Adds functionality to an existing type. Works with classes, structs, enums, and protocols.
func methodName() { }Adds an instance method.
static func methodName() { }Adds a type method (static method).
var name: Type { return expr }Adds a computed property. Stored properties cannot be added.
init(...) { }Adds an initializer. For classes, only convenience initializers can be added.

Sample code

// Add methods to Int
extension Int {
    // Run a closure a given number of times
    func times(_ action: () -> Void) {
        for _ in 0..<self { action() }
    }
    // Computed property that returns the square
    var squared: Int { return self * self }
}

3.times { print("Hello!") }
print("5 squared:", 5.squared)

// Add utility methods to String
extension String {
    var isBlank: Bool { return self.trimmingCharacters(in: .whitespaces).isEmpty }

    func padded(to length: Int, with char: Character = " ") -> String {
        guard self.count < length else { return self }
        return String(repeating: char, count: length - self.count) + self
    }
}

print("  ".isBlank)          // true
print("42".padded(to: 5, with: "0"))  // 00042

Notes

Extensions serve two purposes: adding new functionality and organizing existing code. A common pattern is to split a large class into multiple extensions, grouping each one by protocol conformance.

Stored properties cannot be added in an extension. Computed properties (getter only) are allowed. You also cannot override existing methods in an extension.

You can extend standard library types such as Int, String, and Array, but be careful about naming conflicts with other libraries. The full power of extensions becomes clear when combined with protocol conformance — see extension + protocol for details.

If you find any errors or copyright issues, please .