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 + protocol / Default Implementations

extension + protocol / Default Implementations

By combining extension and protocols, you can retroactively add protocol conformance to existing types (retroactive conformance), or provide default implementations for protocol requirements.

Syntax

// Add protocol conformance to an existing type
extension ExistingTypeName: ProtocolName {
    // Required method implementations
}

// Add a default implementation to a protocol
extension ProtocolName {
    func methodName() { /* default implementation */ }
}

Syntax Overview

SyntaxDescription
extension Type: Protocol { }Retroactively adds protocol conformance to an existing type (retroactive conformance).
extension Protocol { func f() {} }Adds a default implementation to a protocol. Conforming types can omit their own implementation.
extension Protocol where Self: Type { }Adds a conditional implementation that applies only to a specific type.

Sample Code

protocol Describable {
    func describe() -> String
}

// Default implementation
extension Describable {
    func describe() -> String {
        return "This is a \(type(of: self))"
    }
}

// Make Int conform to Describable (retroactive conformance)
extension Int: Describable {
    func describe() -> String {
        return "Integer value: \(self)"
    }
}

// String uses the default implementation
extension String: Describable { }

print(42.describe())
print("Hello".describe())

// Conditional extension using a where clause
protocol Summable {
    static func +(lhs: Self, rhs: Self) -> Self
    static var zero: Self { get }
}

extension Array where Element: Summable {
    func sum() -> Element {
        return reduce(Element.zero, +)
    }
}

extension Int: Summable { static var zero: Int { 0 } }
print([1, 2, 3, 4, 5].sum())

Notes

Combining extension with protocols is one of the most important patterns in Swift. The standard library itself is built on this mechanism — for example, conforming to Comparable automatically gives you <= and >=.

Retroactive conformance — making a type from an external module conform to a protocol from another external module — generates a compiler warning in Swift 5.7 and later. If either the type or the protocol is one you defined yourself, there is no issue.

For the basics of extensions, see Extension Basics.

If you find any errors or copyright issues, please .