Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Extensions

Swift Extensions

An extension can add new functionality to an existing type without modifying its original definition.

The extended type can be a struct, class, enum, or protocol, or even a built-in type like Int or String from the Swift standard library.

All code in this article is based on Swift 6.x and Xcode 16, and the examples can be run directly with the swift command.


What extensions can do

First, look at a capability list to clarify the boundaries of extensions.

Capability Supported Description
Add computed properties Supported Cannot add stored properties
Add instance methods and type methods Supported Add mutating when a struct method needs to modify self
Add initializers Supported Convenience initializers for classes are OK, designated initializers are not
Add subscripts Supported Both reads and writes are supported
Add nested types Supported Enums, structs, and classes are all allowed
Make a type conform to a protocol Supported One of the most common scenarios
Add stored properties Not supported This produces a compile error directly
Add a deinitializer deinit Not supported Can only be written inside a class body
Override existing functionality Not supported Extensions are not inheritance

The syntax for extensions is simple: use the keyword extension followed by a type name, and write the new members inside the braces.

Example

extension ExistingType

{

   

// Add computed properties, methods, initializers, subscripts, and nested types here

}


Extension Computed Properties

Extensions can add computed properties but not stored properties, because stored properties require additional memory layout, and an extension cannot change the existing memory layout of a type.

The example below adds three unit-conversion computed properties to Double.

Example

import Foundation

// Extend Double with computed properties: convert kilometers to meters and centimeters

extension Double

{

    var km

:

Double

{

self

1

_000.0

}

 

// Kilometers

    var m

:

Double

{

self

}

             

// Meters

    var cm

:

Double

{

self

/

100.0

}

   

// Centimeters

}

// Extend Int with an instance method: repeat an operation self times

extension Int

{

    func repetitions

(

task

:

(

)

Void

)

{

       

for

_ in

0

..

<

self

{

task

(

)

}

}

}

let distance

=

3.0

print

(

"(distance) kilometers = (distance.km) meters"

)

print

(

"(distance) kilometers = (distance.cm) centimeters"

)

3

.

repetitions

{

    print

(

"RUNOOB"

)

}

Running result:



3.0 千米 = 3000.0 米

3.0 千米 = 0.03 厘米

RUNOOB

RUNOOB

RUNOOB

The self used inside a computed property is the extended value itself, so 3.0.km is equivalent to 3.0 * 1000.0.


Extension Methods

The repetitions(task:) in the example above is an extension instance method; it takes a closure and executes it repeatedly.

If the extended type is a struct or enum and the method needs to modify the instance itself, it must also be marked mutating.

Example

import Foundation

struct

RunoobCounter

{

    var count

=

0

}

extension RunoobCounter

{

   

// Modifying self's state, must be marked mutating

    mutating func increment

(

)

{

        count

=

1

   

}

   

// Read-only methods do not need mutating

    func describe

(

)

String

{

       

return

"Current count: (count)"

   

}

}

var counter

=

RunoobCounter

(

)

counter.

increment

(

)

counter.

increment

(

)

print

(

counter.

describe

(

)

)

Running result:



当前计数:2

Note:Only struct instances declared with var can call the mutating method. If declared with let , the compiler will report an error.


Extension Initializers

Extensions can add new initializers to a type, making it convenient to create instances in another way.

A struct's memberwise initializer init(width:height:) is generated automatically by the compiler, and an extension can add another initializer that "creates a square from a side length".

Example

import Foundation

// The struct itself only has the memberwise initializer init(width:height:)

struct

RunoobSize

{

    var width

=

0.0

    var height

=

0.0

}

// Add a convenience initializer in the extension that builds a square from a side length

extension RunoobSize

{

    init

(

side

:

Double

)

{

        self.

init

(

width

:

side, height

:

side

)

 

// Must delegate to an existing initializer

   

}

}

let square

=

RunoobSize

(

side

:

5.0

)

print

(

"width = (square.width), height = (square.height)"

)

Running result:



width = 5.0, height = 5.0

An initializer in an extension must ensure that all stored properties are properly initialized, so here it delegates to an existing initializer via self.init(...).

Note:When writing an extension initializer for a class, you can only add convenience initializers, not designated initializers; designated initializers must be written inside the class body.


Extension Subscripts

Extensions can add subscripts to a type, making value-access syntax more natural.

The example below adds a subscript to Int to extract the nth digit of a decimal number, counting from right to left.

Example

import Foundation

// Extend Int with a subscript: extract the digit at digitIndex positions from the right in a decimal number

extension Int

{

    subscript

(

digitIndex

:

Int

)

Int

{

        var decimalBase

=

1

       

for

_ in

0

..

<

digitIndex

{

decimalBase

=

10

}

return

(

self

/

decimalBase

)

%

10

}

}

let number

=

746381295

print

(

number

[

0

]

, number

[

1

]

, number

[

2

]

, number

[

8

]

)

Running result:



5 9 2 7

number[0] is the ones digit 5, number[8] is the highest digit 7, and subscripts are counted from 0.


Extension Nested Types

Extensions can add nested types inside an existing type; a common practice is to place an enum inside the extended type to avoid polluting the global namespace.

Example

import Foundation

// Extension nested types

extension Int

{

   

enum

RunoobKind

{

       

case

negative, zero, positive

   

}

    var runoobKind

:

RunoobKind

{

       

switch

self

{

       

case

0

:

return

.

zero

       

case

let x where x

0

:

return

.

positive

       

default

:

return

.

negative

       

}

   

}

}

func describe

(

_ value

:

Int

)

String

{

   

switch

value.

runoobKind

{

   

case

.

negative

:

return

"(value) is negative"

   

case

.

zero

:

   

return

"(value) is zero"

   

case

.

positive

:

return

"(value) is positive"

   

}

}

print

(

describe

(

7

)

)

print

(

describe

(

0

)

)

print

(

describe

(

42

)

)

Running result:



-7 是负数

0 是零

42 是正数

The full name of the enum RunoobKind is Int.RunoobKind, so this naming will not conflict with other enums of the same name in the project.


Extensions Implementing Protocols

This is the most common use of extensions: a type does not conform to a protocol when it is defined, and conformance is added later through an extension.

The benefit is that the type definition stays concise, and protocol implementations can be split across multiple extensions by functionality.

Example

import Foundation

// The protocol requires one property and one method

protocol RunoobGreetable

{

    var name

:

String

{

get

}

    func greet

(

)

String

}

// The type does not conform to the protocol when defined

struct

RunoobUser

{

    var name

:

String

}

// Conform to the protocol and implement the requirements in an extension

extension RunoobUser

:

RunoobGreetable

{

    func greet

(

)

String

{

       

"Hello, (name)! Welcome to www.runoob.com"

   

}

}

let user

=

RunoobUser

(

name

:

"RUNOOB"

)

print

(

user.

greet

(

)

)

// Let an existing type gain protocol capabilities through an extension

extension String

:

RunoobGreetable

{

    var name

:

String

{

self

}

    func greet

(

)

String

{

"Hello, (self)!"

}

}

print

(

"Runoob"

.

greet

(

)

)

Running result:



Hello, RUNOOB! Welcome to www.runoob.com

Hello, Runoob!

String is a standard library type and we do not have its source code, but we can still make it conform to a custom protocol through an extension.


Extending Generic Types

Generic types can also be extended. An extension can use the original type parameters directly, or you can add a where clause to the extension so that the new functionality is available only under certain conditions.

Example

import Foundation

// Generic struct: a simple stack

struct

RunoobStack

<

Element

{

private

var items

:

[

Element

]

=

[

]

    mutating func push

(

_ item

:

Element

)

{

        items.

append

(

item

)

   

}

    mutating func pop

(

)

Element

?

{

        items.

popLast

(

)

   

}

}

// Normal extension: available for all Element

extension RunoobStack

{

    var top

:

Element

?

{

items.

last

}

    var isEmpty

:

Bool

{

items.

isEmpty

}

}

// Conditional extension: contains is available only when Element conforms to Equatable

extension RunoobStack where Element

:

Equatable

{

    func contains

(

_ item

:

Element

)

Bool

{

        items.

contains

(

item

)

   

}

}

var stack

=

RunoobStack

<

Int

(

)

stack.

push

(

10

)

stack.

push

(

20

)

stack.

push

(

30

)

print

(

"Top element: (stack.top!)"

)

print

(

"Contains 20: (stack.contains(20))"

)

print

(

"Contains 99: (stack.contains(99))"

)

print

(

"Popped an element: (stack.pop()!)"

)

print

(

"Is stack empty: (stack.isEmpty)"

)

Running result:



栈顶元素:30

是否包含 20:true

是否包含 99:false

弹出一个元素:30

栈是否为空:false

contains uses the == comparison, so Element must be constrained to Equatable; on stack types that do not satisfy the condition, this method simply does not appear.


Extensions Cannot Add Stored Properties or Deinitializers

Extensions are only for adding functionality and cannot change a type's storage layout, so they cannot add stored properties or deinitializers.

First, let's see what happens when adding a stored property:

Example

struct

RunoobPoint

{

    var x

=

0

    var y

=

0

}

extension RunoobPoint

{

    var runoobTag

=

"Point"

 

// Adding a stored property in an extension

}

Compile error:



error: extensions must not contain stored properties

Now let's see what happens when adding a deinitializer; even if the extended type is a class, it still will not work:

Example

class

RunoobBox

{

    var value

=

0

}

extension RunoobBox

{

    deinit

{

        print

(

"deinit"

)

   

}

}

Compile error:



error: deinitializers may only be declared within a class, actor, or noncopyable type

A deinitializer must be written inside the class body and cannot be declared in an extension.

Note:Extensions also cannot "override" existing methods or properties of a type. If you define a method with the same name in an extension, the compiler reports a duplicate definition rather than an override.


Retroactive Conformance and @retroactive

Retroactive conformance refers to making a type from module A conform to a protocol from module B inside module C, where neither A nor B is owned by you.

This pattern is legal in itself but carries a risk: if the author of A later makes that type conform to B's protocol as well, the two implementations will conflict. Swift 6 issues a warning for this.

Below, three files are used to simulate three modules. The first file is LibA, which only defines a type:

Example

// Module LibA: defines the RunoobPoint type

public

struct

RunoobPoint

{

   

public

var x

:

Int

   

public

init

(

x

:

Int

)

{

self.

x

=

x

}

}

The second file is LibB, which only defines a protocol:

Example

// Module LibB: defines the RunoobFormattable protocol

public

protocol RunoobFormattable

{

    func runoobFormat

(

)

String

}

The third file is App, where the retroactive conformance is written. At this point, both RunoobPoint and RunoobFormattable are "external types".

Example

import LibA

import LibB

// In the App module, make the type from LibA conform to the protocol from LibB

extension RunoobPoint

:

RunoobFormattable

{

   

public

func runoobFormat

(

)

String

{

"RunoobPoint(x: (x))"

}

}

Type-checking with swiftc produces a warning:



warning: extension declares a conformance of imported type 'RunoobPoint'

to imported protocol 'RunoobFormattable'; this will not behave correctly

if the owners of 'LibA' introduce this conformance in the future

note: add '@retroactive' to silence this warning

Following the hint, adding @retroactive removes the warning and explicitly expresses "I know this conformance is cross-module and may conflict".

Example

import LibA

import LibB

// Explicitly mark the retroactive conformance with @retroactive

extension RunoobPoint

:

@retroactive RunoobFormattable

{

   

public

func runoobFormat

(

)

String

{

"RunoobPoint(x: (x))"

}

}

let point

=

RunoobPoint

(

x

:

42

)

print

(

point.

runoobFormat

(

)

)

Running result:



RunoobPoint(x: 42)

@retroactive is just a "confirmation marker"; it does not change behavior, it only stops the compiler from warning.

Note:If at least one of the type or protocol is defined in your own module, it is a normal conformance, and you neither need nor should add @retroactive. Adding it forcibly will produce a warning 'retroactive' attribute does not apply。


Common questions

Finally, let's answer a few questions that beginners often ask.

Can extensions replace subclasses?

No. Extensions add functionality to a type but cannot change the inheritance relationship between types, nor can they add stored properties, so when you need to store new state, consider inheritance or composition.

Can extensions add default implementations to protocols?

Yes. Write an extension for the protocol and implement the requirements; conformers automatically get the default implementation. This is a protocol-oriented programming technique; for details, see 《Swift Protocol Extensions and Protocol-Oriented Programming》。

Does writing multiple extensions for the same type have any effect?

No effect; the end result is the same as writing all members in a single extension. In practice, extensions are usually split by functionality, for example one extension for protocol conformance and one for formatting methods.

Can static members be used in extensions?

Yes. Extensions can add both instance members and static or class type members, with the same rules as when written inside the type body.

Can a protocol itself be extended?

Yes. This is called a protocol extension, used to provide default implementations or conditional methods. For details, see 《Swift Protocol Extensions and Protocol-Oriented Programming》。