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

Swift Generics

Swift Generics

Generics allow code to be written without binding to a specific type, with the actual type decided only when the code is called.

The same generic function or generic type can handle any type — Int, String, custom structs, and so on — while retaining compile-time type checking.

Array, Dictionary, and Optional in the Swift standard library are all generic types, so you have been using generics all along when working with them.


Why Do We Need Generics

Suppose you want to write a function that swaps the values of two variables. Without generics, you would have to write a separate version for each type.

Example

// Version that only supports Int

func runoobSwapInt

(

_ a

:

inout Int, _ b

:

inout Int

)

{

    let temp

=

a

    a

=

b

    b

=

temp

}

// Version that only supports String

func runoobSwapString

(

_ a

:

inout String, _ b

:

inout String

)

{

    let temp

=

a

    a

=

b

    b

=

temp

}

The two pieces of code have exactly the same logic, differing only in type. The more types there are, the more duplicated code there is.

Generics turn the type into a "parameter" as well, so a single piece of code can cover all types.


Generic functions

Declare type parameters in angle brackets after the function name, for example , after which T can be used just like a normal type.

The runoobSwap below supports both strings and integers, and the compiler automatically infers the actual type of T at the call site.

Example

import Foundation

// Generic function: swap the values of two variables of the same type

func runoobSwap

<

T

(

_ a

:

inout T, _ b

:

inout T

)

{

    let temp

=

a

    a

=

b

    b

=

temp

}

var site1

=

"www.runoob.com"

var site2

=

"RUNOOB"

runoobSwap

(

&

site1,

&

site2

)

print

(

"(site1) / (site2)"

)

// The type parameter T is inferred as Int

var x

=

10

var y

=

99

runoobSwap

(

&

x,

&

y

)

print

(

"x = (x), y = (y)"

)

Running result:



RUNOOB / www.runoob.com

x = 99, y = 10

If you want the two parameters to be of different types, you need to declare two type parameters, for example func f(_ a: T, _ b: U)。


Type Parameters and Type Inference

A type parameter is just a placeholder, and its actual type is determined by the arguments at the call site.

The generic function below searches for an element in an array and returns its index. Because it uses the == comparison, it includes the constraint T: Equatable.

Example

import Foundation

// Generic function: find the index of an element in an array

func runoobIndex

<

T

:

Equatable

(

of value

:

T, in array

:

[

T

]

)

Int

?

{

   

for

(

index, item

)

in array.

enumerated

(

)

where item

==

value

{

       

return

index

   

}

   

return

nil

}

let sites

=

[

"baidu"

,

"runoob"

,

"taobao"

]

if

let i

=

runoobIndex

(

of

:

"runoob"

, in

:

sites

)

{

    print

(

"The index of runoob is (i)"

)

}

Running result:



runoob 的下标是 1

At the call site T is inferred as String; if [Int] is passed in, T becomes Int, with no extra code needed.


Generic type

Not only functions — structs, classes, and enums can all be generic. Simply declare type parameters after the type name.

The generic stack RunoobStack below can hold any type, but the element types within a single instance must be consistent.

Example

import Foundation

// Generic struct: no restriction on the type of Element

struct

RunoobStack

<

Element

{

private

var items

:

[

Element

]

=

[

]

    mutating func push

(

_ item

:

Element

)

{

        items.

append

(

item

)

   

}

    mutating func pop

(

)

Element

?

{

        items.

popLast

(

)

   

}

    var top

:

Element

?

{

items.

last

}

}

var intStack

=

RunoobStack

<

Int

(

)

// Explicitly specify the type parameter

intStack.

push

(

1

)

intStack.

push

(

2

)

intStack.

push

(

3

)

print

(

"Top: (intStack.top!)"

)

var strStack

=

RunoobStack

<

String

(

)

// Another completely independent type

strStack.

push

(

"runoob"

)

strStack.

push

(

"RUNOOB"

)

print

(

"Top: (strStack.top!)"

)

print

(

"Popped one: (strStack.pop()!)"

)

print

(

"Top: (strStack.top!)"

)

// Generic class

class

RunoobBox

<

Value

{

    var value

:

Value

    init

(

_ value

:

Value

)

{

        self.

value

=

value

   

}

}

let box

=

RunoobBox

(

"Runoob Tutorial"

)

 

// Value is inferred as String

print

(

box.

value

)

Running result:



栈顶:3

栈顶:RUNOOB

弹出一个:RUNOOB

栈顶:runoob

Runoob Tutorial

RunoobStack and RunoobStack are two completely different types to the compiler and cannot be assigned to each other.

Note:When creating a generic instance, if the type cannot be inferred from context, you must write it explicitly, for example RunoobStack(); if you write RunoobStack() and the type information is not used later, the compiler will report "generic parameter could not be inferred".


Type Constraints

By default, a type parameter can be any type, so the operations you can call on it are very limited.

With type constraints added, you can use members provided by the constraining protocol on T, such as comparing values with Comparable.

Example

import Foundation

// Type constraint: T must conform to Comparable

func runoobMax

<

T

:

Comparable

(

_ a

:

T, _ b

:

T

)

T

{

   

return

a

b

?

a

:

b

}

print

(

runoobMax

(

3

,

9

)

)

print

(

runoobMax

(

"apple"

,

"runoob"

)

)

// Multiple constraints: T conforms to both Hashable and CustomStringConvertible

func runoobInfo

<

T

:

Hashable

&

CustomStringConvertible

(

_ value

:

T

)

String

{

   

return

"Value: (value), description: (value.description)"

}

print

(

runoobInfo

(

"RUNOOB"

)

)

// Constrain a type to be a subclass of a certain class

class

RunoobBase

{

}

class

RunoobSub

:

RunoobBase

{

}

func runoobCheck

<

T

:

RunoobBase

(

_ item

:

T

)

String

{

   

return

"Type is (type(of: item))"

}

print

(

runoobCheck

(

RunoobSub

(

)

)

)

Running result:



9

runoob

值:RUNOOB,描述:RUNOOB

类型是 RunoobSub

There are two common ways to write constraints, with the same effect; the former is more concise.

Syntax Example Description
Constraints in angle brackets func f(_ x: T) Most common; the constraint is written after the type parameter
where clause constraints func f(_ x: T) where T: Comparable More readable when constraints are complex
Protocol composition T: Hashable & CustomStringConvertible Use & to combine multiple protocols
Class constraint T: RunoobBase Requires T to be that class or a subclass

where clause

When there are many constraints, or the constrained object is not a single type parameter, a where clause expresses it more clearly.

The following demonstrates both uses: adding conditions to a generic extension, and adding constraints to a generic function.

Example

import Foundation

// Generic struct: stack

struct

RunoobStack

<

Element

{

private

var items

:

[

Element

]

=

[

]

    mutating func push

(

_ item

:

Element

)

{

items.

append

(

item

)

}

    var all

:

[

Element

]

{

items

}

}

// Constrain with a where clause: contains is available only when Element conforms to Equatable

extension RunoobStack where Element

:

Equatable

{

    func contains

(

_ item

:

Element

)

Bool

{

        items.

contains

(

item

)

   

}

}

// Constrain with a where clause: the maximum value is available only when Element conforms to Comparable

extension RunoobStack where Element

:

Comparable

{

    func maxElement

(

)

Element

?

{

        items.

max

(

)

   

}

}

var stack

=

RunoobStack

<

Int

(

)

stack.

push

(

30

)

stack.

push

(

10

)

stack.

push

(

20

)

print

(

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

)

print

(

"Max value: (stack.maxElement()!)"

)

// where clause in a function

func runoobPairs

<

C1

:

Collection, C2

:

Collection

(

_ a

:

C1, _ b

:

C2

)

Int

where C1.

Element

:

Equatable, C1.

Element

==

C2.

Element

{

    var count

=

0

   

for

x in a

{

       

if

b.

contains

(

where

:

{

$

0

==

x

}

)

{

            count

=

1

       

}

   

}

   

return

count

}

print

(

"Number of matching elements: (runoobPairs([1, 2, 3, 4], [2, 4, 6]))"

)

Running result:



是否包含 10:true

最大值:30

相同元素个数:2

The where clause on the function also writes C1.Element == C2.Element, indicating that the element types of the two collections must be the same so that they can be compared with each other.


Associated Types associatedtype

A protocol itself cannot have type parameters, but it can use associatedtype to declare a "placeholder type", with the concrete type decided by the conformer.

The protocol below requires conformers to provide the element type Item, an add method, a count property, and a subscript.

Example

import Foundation

// Define a protocol with an associated type

protocol RunoobContainer

{

    associatedtype Item                      

// Associated type; the concrete type is decided by the conformer

    mutating func append

(

_ item

:

Item

)

    var count

:

Int

{

get

}

    subscript

(

i

:

Int

)

Item

{

get

}

}

// Conform to the protocol: Item is inferred as Int

struct

RunoobIntList

:

RunoobContainer

{

   

private

var items

:

[

Int

]

=

[

]

    mutating func append

(

_ item

:

Int

)

{

        items.

append

(

item

)

   

}

    var count

:

Int

{

items.

count

}

    subscript

(

i

:

Int

)

Int

{

items

[

i

]

}

}

var list

=

RunoobIntList

(

)

list.

append

(

100

)

list.

append

(

200

)

list.

append

(

300

)

print

(

"Element count: (list.count)"

)

print

(

"First element: (list[0])"

)

// Explicitly specify the associated type with a type alias

struct

RunoobStringList

:

RunoobContainer

{

    typealias Item

=

String          

// Write the associated type explicitly

   

private

var items

:

[

String

]

=

[

]

    mutating func append

(

_ item

:

String

)

{

items.

append

(

item

)

}

    var count

:

Int

{

items.

count

}

    subscript

(

i

:

Int

)

String

{

items

[

i

]

}

}

var names

=

RunoobStringList

(

)

names.

append

(

"Runoob"

)

names.

append

(

"RUNOOB"

)

print

(

"Element count: (names.count)"

)

print

(

"Second element: (names[1])"

)

// A generic function working with an associated-type protocol

func runoobTotal

<

C

:

RunoobContainer

(

_ container

:

C

)

Int

{

   

return

container.

count

}

print

(

"Total: (runoobTotal(list))"

)

Running result:



元素个数:3

第一个元素:100

元素个数:2

第二个元素:RUNOOB

总数:3

RunoobIntList does not write a typealias; the compiler automatically infers Item = Int from the method signatures of append and the subscript.

Note:If a protocol has both associatedtype and you want a generic function to accept it, usually write the associated type as a type parameter C: RunoobContainer, letting the compiler infer it; do not try to write directly RunoobContainer as a concrete type.


Generic Extensions

Generic types can be extended; an extension can use the original type parameters directly and can also add extra conditions via where.

This is the same mechanism as the where clause discussed above, differing only in that the syntax is split into "normal extensions" and "conditional extensions".

Example

import Foundation

struct

RunoobStack

<

Element

{

private

var items

:

[

Element

]

=

[

]

    mutating func push

(

_ item

:

Element

)

{

items.

append

(

item

)

}

}

// Normal extension: available for all Element

extension RunoobStack

{

    var isEmpty

:

Bool

{

items.

isEmpty

}

    var top

:

Element

?

{

items.

last

}

}

// Conditional extension: a formatting method is added only when Element is String

extension RunoobStack where Element

==

String

{

    func joined

(

)

String

{

        items.

joined

(

separator

:

" - "

)

   

}

}

var stack

=

RunoobStack

<

String

(

)

stack.

push

(

"Runoob"

)

stack.

push

(

"RUNOOB"

)

stack.

push

(

"www.runoob.com"

)

print

(

"Is empty: (stack.isEmpty)"

)

print

(

"Top: (stack.top!)"

)

print

(

"Joined result: (stack.joined())"

)

Running result:



是否为空:false

栈顶:www.runoob.com

拼接结果:Runoob - RUNOOB - www.runoob.com

where Element == String is an exact equality constraint, stricter than Element: Equatable, and applies only to stacks whose element type is exactly String.


Common questions

Let's answer a few commonly confused points in one place.

What is the division of labor between generics and protocols?

Generics determine the concrete type at compile time with no runtime overhead, making them suitable for "one algorithm handling multiple types"; protocols, on the other hand, describe abstract capabilities, and the two are often used together.

When to use generics and when to use any

If the call site can determine the concrete type and you want to preserve type information, use generics; if you need to hold different concrete types at runtime, even in the same array, use the existential type any. For details, see 《Swift some and any》。

Do generics affect performance?

No. Swift uses generic specialization to generate dedicated code for concrete types at compile time, so it is no slower at runtime than a hand-written version.

Why can't two values be compared directly in generics?

Because a type parameter does not guarantee support for == by default, you need to add the constraint T: Equatable before the compiler allows the equality comparison.