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

Swift protocols

Swift protocols

A protocol is a "list of capabilities" that only specifies which properties, methods, and initializers must be provided, without caring how they are implemented.

Classes, structs, and enums can all conform to protocols, allowing completely different types of objects to be handled by the same code.

Swift is a protocol-oriented language; Sequence, Collection, Equatable, and Codable in the standard library are all protocols.


Protocol definition and conformance

Define a protocol with protocol; to conform, write the protocol name after the type name, separated by a colon.

A type can conform to multiple protocols at once, separated by commas.

Example

import Foundation

// A protocol only describes "what is needed", providing no implementation

protocol RunoobDescribable

{

    var name

:

String

{

get

}

    func describe

(

)

String

}

struct

RunoobSite

:

RunoobDescribable

{

    var name

:

String

    func describe

(

)

String

{

       

return

"Site: (name)"

   

}

}

struct

RunoobUser

:

RunoobDescribable

{

    var name

:

String

    func describe

(

)

String

{

       

return

"User: (name)"

   

}

}

let items

:

[

any RunoobDescribable

]

=

[

    RunoobSite

(

name

:

"www.runoob.com"

)

,

    RunoobUser

(

name

:

"RUNOOB"

)

]

for

item in items

{

    print

(

item.

describe

(

)

)

}

Running result:



站点:www.runoob.com

用户:RUNOOB

The array's element type is written as any RunoobDescribable, meaning "any type that conforms to this protocol", so two structs can be placed in the same array.

When iterating and calling describe(), what actually runs is each type's own implementation; this is dynamic dispatch.


Property requirements

Properties in a protocol are written with just a name and type, followed by { get } or { get set } to indicate readability and writability.

The protocol does not care whether it is a stored or computed property, only whether it satisfies the read/write requirement.

Example

import Foundation

protocol RunoobNamed

{

    var name

:

String

{

get

}

           

// Read-only requirement

    var displayName

:

String

{

get set

}

 

// Read-write requirement

}

struct

RunoobTag

:

RunoobNamed

{

    let name

:

String                    

// A let stored property satisfies the get requirement

    var displayName

:

String

}

class

RunoobCategory

:

RunoobNamed

{

    var name

:

String

    var displayName

:

String

{

        didSet

{

print

(

"displayName changed to (displayName)"

)

}

   

}

    init

(

name

:

String, displayName

:

String

)

{

        self.

name

=

name

        self.

displayName

=

displayName

   

}

}

let tag

=

RunoobTag

(

name

:

"swift"

, displayName

:

"Swift Tutorial"

)

print

(

tag.

displayName

)

let category

=

RunoobCategory

(

name

:

"swift"

, displayName

:

"Swift"

)

category.

displayName

=

"Swift 6"

Running result:



Swift 教程

displayName 改为 Swift 6

The read-only requirement { get } is the most lenient: let stored properties, read-only computed properties, and read-write properties can all satisfy it.

The read-write requirement { get set } must provide both get and set, so a let constant cannot satisfy it.

Note:The property { get set } in a protocol describes "the interface the conformer must provide", not "the protocol itself has a readable and writable property". A protocol stores no values itself.


Method requirements and mutating

A method requirement is written in a protocol with just the signature, without braces or a body.

Parameter label rules are the same as for ordinary functions: all parameters have external labels by default, and to omit one you must explicitly write _.

If a method modifies the conformer's own state, mark it mutating in the protocol.

Example

import Foundation

protocol RunoobCounter

{

    var count

:

Int

{

get

}

    mutating func increment

(

)

 

// When a value type conforms, the implementation must be marked mutating

}

struct

RunoobTally

:

RunoobCounter

{

    var count

=

0

    mutating func increment

(

)

{

        count

=

1

   

}

}

class

RunoobSharedCounter

:

RunoobCounter

{

    var count

=

0

    func increment

(

)

{

         

// Classes do not need mutating when conforming

        count

=

1

   

}

}

var tally

=

RunoobTally

(

)

tally.

increment

(

)

tally.

increment

(

)

print

(

"Struct count: (tally.count)"

)

let shared

=

RunoobSharedCounter

(

)

shared.

increment

(

)

print

(

"Class count: (shared.count)"

)

Running result:



结构体计数:2

类计数:1

The struct's increment() must be written as mutating because it modifies its own stored properties.

A class's methods already have reference semantics, so modifying properties needs no mutating; therefore the mutating requirement in a protocol does not apply to classes.

Note:If you use a let let-declared struct constant to call a mutating method, it is a compile-time error, because a constant cannot be modified.


Initializer requirements and required

A protocol can require conformers to implement an initializer, written as init(parameters), again without a body.

When a class conforms to a protocol with an initializer requirement, the initializer must be marked required so subclasses are forced to implement it.

Example

import Foundation

protocol RunoobInitable

{

    init

(

name

:

String

)

}

class

RunoobNode

:

RunoobInitable

{

    var name

:

String

    required init

(

name

:

String

)

{

 

// When a class conforms to a protocol with an initializer requirement, it must write required

        self.

name

=

name

   

}

    func describe

(

)

String

{

"Node (name)"

}

}

class

RunoobLeaf

:

RunoobNode

{

    var level

:

Int

    init

(

name

:

String, level

:

Int

)

{

        self.

level

=

level

        super.

init

(

name

:

name

)

   

}

   

// A subclass that defines its own designated initializer does not automatically inherit the superclass initializer, so it must reimplement required init

    required init

(

name

:

String

)

{

        self.

level

=

1

        super.

init

(

name

:

name

)

   

}

    override func describe

(

)

String

{

"Leaf node (name) (level (level))"

}

}

let leaf

:

any RunoobInitable

=

RunoobLeaf

(

name

:

"runoob"

, level

:

2

)

if

let node

=

leaf as

?

RunoobLeaf

{

    print

(

node.

describe

(

)

)

}

Running result:



叶子节点 runoob(第 2 层)

RunoobNode conforms to the protocol directly, so its init(name:) must be marked required.

RunoobLeaf defines its own designated initializer, so it no longer automatically inherits the superclass initializer and must implement required init itself.

If a subclass defines no designated initializer at all, it can directly inherit the superclass's required init and need not rewrite it.


Protocols as types and any Protocol

A protocol can be used as a type: protocol names can be written for variables, array elements, function parameters, and return values.

Since Swift 5.7, the official recommendation is to write any explicitly before a protocol type, indicating an existential type.

Its meaning is "a box containing some unknown concrete type, known only to conform to this protocol".

Example

import Foundation

protocol RunoobLogger

{

    func

log

(

_ message

:

String

)

}

struct

RunoobConsoleLogger

:

RunoobLogger

{

    func

log

(

_ message

:

String

)

{

        print

(

"[Console] (message)"

)

   

}

}

struct

RunoobFileLogger

:

RunoobLogger

{

    var fileName

:

String

    func

log

(

_ message

:

String

)

{

        print

(

"[(fileName)] (message)"

)

   

}

}

// Protocol as a type: array elements can be any type conforming to RunoobLogger

var loggers

:

[

any RunoobLogger

]

=

[

    RunoobConsoleLogger

(

)

,

    RunoobFileLogger

(

fileName

:

"runoob.log"

)

]

loggers.

append

(

RunoobConsoleLogger

(

)

)

for

logger in loggers

{

    logger.

log

(

"Log from www.runoob.com"

)

}

let single

:

any RunoobLogger

=

RunoobFileLogger

(

fileName

:

"www.runoob.com.log"

)

single.

log

(

"RUNOOB"

)

Running result:



[控制台] 来自 www.runoob.com 的日志

[runoob.log] 来自 www.runoob.com 的日志

[控制台] 来自 www.runoob.com 的日志

[www.runoob.com.log] RUNOOB

A variable of an any type can only call members declared in the protocol and cannot access other properties of the concrete type.

If you need to use capabilities of the concrete type, you can first downcast with as?, see "Swift Type Casting》。

Note:Do not write all protocol parameters as any P. If the function only needs to call protocol members, using a generic func f(_ value: T) lets the compiler do static dispatch with better performance. The difference between the two is described in "Swift some and any》。


Protocol inheritance

A protocol can inherit from another protocol, combining multiple requirements into a larger contract.

The RunoobPerson below requires name, age, and greet() at once; conforming to it is equivalent to conforming to the other two protocols simultaneously.

Example

import Foundation

protocol RunoobNamed2

{

    var name

:

String

{

get

}

}

protocol RunoobAged

{

    var age

:

Int

{

get

}

}

// Protocol inheritance: RunoobPerson requires name, age, and greet() at once

protocol RunoobPerson

:

RunoobNamed2, RunoobAged

{

    func greet

(

)

}

struct

RunoobStudent

:

RunoobPerson

{

    var name

:

String

    var age

:

Int

    func greet

(

)

{

        print

(

"I am (name), (age) years old"

)

   

}

}

// Protocol composition: A & B means satisfying both protocols at once

func showInfo

(

_ value

:

any RunoobNamed2

&

RunoobAged

)

{

    print

(

"(value.name) / (value.age)"

)

}

let student

=

RunoobStudent

(

name

:

"Xiao Ming"

, age

:

18

)

student.

greet

(

)

showInfo

(

student

)

Running result:



我是 小明,今年 18 岁

小明 / 18

Protocol inheritance is written with a colon followed by multiple protocol names; it looks like class inheritance syntax, but a protocol can inherit from several.

A protocol cannot inherit from a class; only classes can be inherited by classes.


Protocol composition

Protocol composition uses & to combine multiple protocols into a temporary type, meaning "satisfying all these protocols at once".

It is often used for function parameters: when you don't want to create a new protocol for every combination, just write the composition.

The showInfo above already demonstrated any RunoobNamed2 & RunoobAged, whose argument must have both name and age.

A protocol composition can also include a class name, meaning "must be a subclass of this class and also conform to these protocols".


Class-only protocols with AnyObject

If a protocol should only be conformed to by classes, make it inherit from AnyObject.

The benefit is that the protocol type can safely do reference comparison and weak references, because it is guaranteed to be a reference type.

Example

import Foundation

// Class-only protocol: only classes can conform, neither structs nor enums

protocol RunoobClassOnly

:

AnyObject

{

    var identifier

:

String

{

get set

}

}

class

RunoobViewModel

:

RunoobClassOnly

{

    var identifier

:

String

    init

(

identifier

:

String

)

{

self.

identifier

=

identifier

}

}

var vm

:

any RunoobClassOnly

=

RunoobViewModel

(

identifier

:

"home"

)

let other

=

RunoobViewModel

(

identifier

:

"runoob"

)

print

(

vm

===

other

)

vm

=

other

print

(

vm.

identifier

)

print

(

vm

===

other

)

Running result:



false

runoob

true

Because the protocol is constrained to AnyObject, the compiler knows vm must be a class instance, so it allows direct identity comparison with ===.

Note:The correct way to write a class-only protocol is protocol P: AnyObject. A common pattern in old tutorials was to make the protocol inherit from class , which was early Swift syntax and is now an error; do not use it.


Common questions

Below are some common questions about using protocols.

Can a protocol provide default implementations for members?

Yes, but they must be written in a protocol extension, not in the protocol body.

This topic is covered in a separate article, see "Swift Protocol Extensions and Protocol-Oriented Programming》。

Can a protocol contain stored properties?

No. A protocol can only declare read/write requirements for properties; it cannot declare stored properties or property default values.

The conforming type decides for itself whether to use a stored or computed property to satisfy the requirement.

When a struct conforms to a protocol with a mutating requirement, can it be changed to a normal method?

No. If the protocol writes mutating, a value type implementation must also write mutating, or it is a compile-time error.

Classes are not subject to this restriction; a class method can satisfy the requirement without mutating.

How many protocols can a type conform to?

There is no limit; just list the protocol names one by one with commas.

If multiple protocols have members with the same name, a call may need to explicitly specify which protocol's version to use.

What is the difference between a protocol and an abstract class?

An abstract class can only be inherited by classes, while a protocol can be conformed to by classes, structs, and enums, making it more widely applicable.

Swift has no dedicated abstract keyword; when shared implementation is needed, a protocol plus a protocol extension is typically used instead.