Skip to Content
The Swift Programming Language

Protocols协议

Define requirements that conforming types must implement.

定义遵循协议的类型必须实现的要求。

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

协议(Protocol) 定义了满足特定任务或功能所需的方法、属性和其他要求的蓝图。类、结构体或枚举可以 采用(adopt) 该协议,并提供协议要求的具体实现。任何满足协议要求的类型都被称为 遵循(conform) 该协议。

In addition to specifying requirements that conforming types must implement, you can extend a protocol to implement some of these requirements or to implement additional functionality that conforming types can take advantage of.

除了声明所遵循类型必须实现的要求之外,你还可以通过对协议进行扩展来实现一部分要求或附加功能,这样遵循协议的类型就能够使用这些功能。

Protocol Syntax 协议语法

You define protocols in a very similar way to classes, structures, and enumerations:

协议的定义方式与类、结构体和枚举的定义非常相似:

protocol SomeProtocol {
    // protocol definition goes here
}

Custom types state that they adopt a particular protocol by placing the protocol's name after the type's name, separated by a colon, as part of their definition. Multiple protocols can be listed, and are separated by commas:

要让自定义类型遵循某个协议,在定义类型时,需要在类型名称后加上协议名称,中间以冒号(:)分隔。遵循多个协议时,各协议之间用逗号(,)分隔:

struct SomeStructure: FirstProtocol, AnotherProtocol {
    // structure definition goes here
}

If a class has a superclass, list the superclass name before any protocols it adopts, followed by a comma:

如果一个类拥有父类,应该将父类名放在任何遵循的协议名之前,以逗号分隔:

class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
    // class definition goes here
}

Note · 注意

Because protocols are types, begin their names with a capital letter (such as FullyNamed and RandomNumberGenerator) to match the names of other types in Swift (such as Int, String, and Double).

由于协议是类型,它们的名称应以大写字母开头(如 FullyNamed 和 RandomNumberGenerator),以与 Swift 中其他类型的命名规范(如 Int、String 和 Double)保持一致。

Property Requirements 属性要求

A protocol can require any conforming type to provide an instance property or type property with a particular name and type. The protocol doesn't specify whether the property should be a stored property or a computed property --- it only specifies the required property name and type. The protocol also specifies whether each property must be gettable or gettable and settable.

协议可以要求遵循协议的类型提供特定名称和类型的实例属性或类型属性。协议不指定属性是存储属性还是计算属性,它只指定属性的名称和类型。此外,协议还指定属性是可读的还是可读写的。

If a protocol requires a property to be gettable and settable, that property requirement can't be fulfilled by a constant stored property or a read-only computed property. If the protocol only requires a property to be gettable, the requirement can be satisfied by any kind of property, and it's valid for the property to be also settable if this is useful for your own code.

如果协议要求属性可读写,那么该属性不能是常量属性或只读的计算属性。如果协议只要求属性是可读的,那么该属性不仅可以是可读的,如果你自己的代码需要的话,还可以是可写的。

Property requirements are always declared as variable properties, prefixed with the var keyword. Gettable and settable properties are indicated by writing { get set } after their type declaration, and gettable properties are indicated by writing { get }.

属性要求总是声明为变量属性,用 var 关键字作为前缀。在类型声明后加上 { get set } 来表示属性是可读可写的,可读属性则用 { get } 来表示。

protocol SomeProtocol {
    var mustBeSettable: Int { get set }
    var doesNotNeedToBeSettable: Int { get }
}

Always prefix type property requirements with the static keyword when you define them in a protocol. This rule pertains even though type property requirements can be prefixed with the class or static keyword when implemented by a class:

在协议中定义类型属性时,总是使用 static 关键字作为前缀。当一个类遵循协议时,除了 static 关键字,还可以使用 class 关键字来声明类型属性:

protocol AnotherProtocol {
    static var someTypeProperty: Int { get set }
}

Here's an example of a protocol with a single instance property requirement:

如下所示,这是一个只含有一个实例属性要求的协议:

protocol FullyNamed {
    var fullName: String { get }
}

The FullyNamed protocol requires a conforming type to provide a fully qualified name. The protocol doesn't specify anything else about the nature of the conforming type --- it only specifies that the type must be able to provide a full name for itself. The protocol states that any FullyNamed type must have a gettable instance property called fullName, which is of type String.

FullyNamed 协议除了要求遵循协议的类型提供 fullName 属性外,并没有其他特别的要求。这个协议表示,任何遵循 FullyNamed 的类型,都必须有一个可读的 String 类型的实例属性 fullName。

Here's an example of a simple structure that adopts and conforms to the FullyNamed protocol:

下面是一个遵循 FullyNamed 协议的简单结构体:

struct Person: FullyNamed {
    var fullName: String
}
let john = Person(fullName: "John Appleseed")
// john.fullName is "John Appleseed"

This example defines a structure called Person, which represents a specific named person. It states that it adopts the FullyNamed protocol as part of the first line of its definition.

这个例子中定义了一个叫做 Person 的结构体,用来表示一个具有名字的人。它在定义的第一行声明了它遵循 FullyNamed 协议。

Each instance of Person has a single stored property called fullName, which is of type String. This matches the single requirement of the FullyNamed protocol, and means that Person has correctly conformed to the protocol. (Swift reports an error at compile time if a protocol requirement isn't fulfilled.)

每个 Person 实例都有一个 String 类型的存储属性 fullName。这正好满足了 FullyNamed 协议的要求,也就意味着 Person 结构体正确地遵循了协议。(如果协议要求未被完全满足,Swift 在编译时会报错。)

Here's a more complex class, which also adopts and conforms to the FullyNamed protocol:

下面是一个更为复杂的类,它采用并遵循了 FullyNamed 协议:

class Starship: FullyNamed {
    var prefix: String?
    var name: String
    init(name: String, prefix: String? = nil) {
        self.name = name
        self.prefix = prefix
    }
    var fullName: String {
        return (prefix != nil ? prefix! + " " : "") + name
    }
}
var ncc1701 = Starship(name: "Enterprise", prefix: "USS")
// ncc1701.fullName is "USS Enterprise"

This class implements the fullName property requirement as a computed read-only property for a starship. Each Starship class instance stores a mandatory name and an optional prefix. The fullName property uses the prefix value if it exists, and prepends it to the beginning of name to create a full name for the starship.

Starship 类把 fullName 作为只读的计算属性来实现。每一个 Starship 类的实例都有一个名为 name 的非可选属性和一个名为 prefix 的可选属性。当 prefix 存在时,计算属性 fullName 会将 prefix 插入到 name 之前,从而得到一个带有 prefix 的 fullName。

Method Requirements 方法要求

Protocols can require specific instance methods and type methods to be implemented by conforming types. These methods are written as part of the protocol's definition in exactly the same way as for normal instance and type methods, but without curly braces or a method body. Variadic parameters are allowed, subject to the same rules as for normal methods. Default values, however, can't be specified for method parameters within a protocol's definition.

协议可以要求遵循协议的类型实现某些指定的实例方法和类方法。这些方法的编写方式与普通实例方法和类型方法完全相同,都写在协议定义的一部分中,但没有大括号或方法主体。协议允许使用可变参数,和普通方法的定义方式相同。但是,不能在协议定义中为方法参数指定默认值。

As with type property requirements, you always prefix type method requirements with the static keyword when they're defined in a protocol. This is true even though type method requirements are prefixed with the class or static keyword when implemented by a class:

正如属性要求中所述,在协议中定义类方法的时候,总是使用 static 关键字作为前缀。即使在类中实现时,类方法要求使用 class 或 static 作为关键字前缀,这条规则仍然适用:

protocol SomeProtocol {
    static func someTypeMethod()
}

The following example defines a protocol with a single instance method requirement:

下面的例子定义了一个只含有一个实例方法的协议:

protocol RandomNumberGenerator {
    func random() -> Double
}

This protocol, RandomNumberGenerator, requires any conforming type to have an instance method called random, which returns a Double value whenever it's called. Although it's not specified as part of the protocol, it's assumed that this value will be a number from 0.0 up to (but not including) 1.0.

RandomNumberGenerator 协议要求遵循协议的类型必须拥有一个名为 random,返回值类型为 Double 的实例方法。尽管这里并未指明,但是我们假设返回值是从 0.0 到(但不包括)1.0。

The RandomNumberGenerator protocol doesn't make any assumptions about how each random number will be generated --- it simply requires the generator to provide a standard way to generate a new random number.

RandomNumberGenerator 协议并不关心每一个随机数是怎样生成的 —— 它只要求生成器提供一种标准的方式来生成新的随机数。

Here's an implementation of a class that adopts and conforms to the RandomNumberGenerator protocol. This class implements a pseudorandom number generator algorithm known as a linear congruential generator:

这里有一个采用并遵循 RandomNumberGenerator 协议的类。该类实现了一个叫做 线性同余生成器(linear congruential generator) 的伪随机数算法。

class LinearCongruentialGenerator: RandomNumberGenerator {
    var lastRandom = 42.0
    let m = 139968.0
    let a = 3877.0
    let c = 29573.0
    func random() -> Double {
        lastRandom = ((lastRandom * a + c)
            .truncatingRemainder(dividingBy:m))
        return lastRandom / m
    }
}
let generator = LinearCongruentialGenerator()
print("Here's a random number: \(generator.random())")
// Prints "Here's a random number: 0.3746499199817101".
print("And another one: \(generator.random())")
// Prints "And another one: 0.729023776863283".

Mutating Method Requirements 变值方法要求

It's sometimes necessary for a method to modify (or mutate) the instance it belongs to. For instance methods on value types (that is, structures and enumerations) you place the mutating keyword before a method's func keyword to indicate that the method is allowed to modify the instance it belongs to and any properties of that instance. This process is described in Modifying Value Types from Within Instance Methods.

有时需要在方法中改变(或 变值(mutate) )方法所属的实例。例如,在值类型(即结构体和枚举)的实例方法中,将 mutating 关键字作为方法的前缀,写在 func 关键字之前,表示可以在该方法中修改它所属的实例以及实例的任意属性的值。这一过程在 从实例方法内部修改值类型 章节中有详细描述。

If you define a protocol instance method requirement that's intended to mutate instances of any type that adopts the protocol, mark the method with the mutating keyword as part of the protocol's definition. This enables structures and enumerations to adopt the protocol and satisfy that method requirement.

如果你在协议中定义了一个实例方法,该方法会改变遵循该协议的类型的实例,那么在定义协议时需要在方法前加 mutating 关键字。这使得结构体和枚举能够遵循此协议并满足此方法要求。

Note · 注意

If you mark a protocol instance method requirement as mutating, you don't need to write the mutating keyword when writing an implementation of that method for a class. The mutating keyword is only used by structures and enumerations.

实现协议中的 mutating 方法时,若是类类型,则不用写 mutating 关键字。mutating 关键字只用于结构体和枚举。

The example below defines a protocol called Togglable, which defines a single instance method requirement called toggle. As its name suggests, the toggle() method is intended to toggle or invert the state of any conforming type, typically by modifying a property of that type.

如下所示,Togglable 协议只定义了一个名为 toggle 的实例方法。顾名思义,toggle() 方法将改变实例属性,从而切换遵循该协议类型的实例的状态。

The toggle() method is marked with the mutating keyword as part of the Togglable protocol definition, to indicate that the method is expected to mutate the state of a conforming instance when it's called:

toggle() 方法在 Togglable 协议的定义中使用 mutating 关键字标记,这表明该方法在被调用时预计会改变遵循协议的实例的状态:

protocol Togglable {
    mutating func toggle()
}

If you implement the Togglable protocol for a structure or enumeration, that structure or enumeration can conform to the protocol by providing an implementation of the toggle() method that's also marked as mutating.

当使用枚举或结构体来实现 Togglable 协议时,需要提供一个被标记为 mutating 的 toggle() 方法。

The example below defines an enumeration called OnOffSwitch. This enumeration toggles between two states, indicated by the enumeration cases on and off. The enumeration's toggle implementation is marked as mutating, to match the Togglable protocol's requirements:

下面定义了一个名为 OnOffSwitch 的枚举。这个枚举在两种状态之间进行切换,用枚举成员 on 和 off 表示。枚举的 toggle 实现被标记为 mutating,以满足 Togglable 协议的要求:

enum OnOffSwitch: Togglable {
    case off, on
    mutating func toggle() {
        switch self {
        case .off:
            self = .on
        case .on:
            self = .off
        }
    }
}
var lightSwitch = OnOffSwitch.off
lightSwitch.toggle()
// lightSwitch is now equal to .on

Initializer Requirements 构造器要求

Protocols can require specific initializers to be implemented by conforming types. You write these initializers as part of the protocol's definition in exactly the same way as for normal initializers, but without curly braces or an initializer body:

协议可以要求遵循协议的类型实现指定的构造器。你可以像编写普通构造器那样,在协议的定义里写下构造器的声明,但不需要写花括号和构造器的实体:

protocol SomeProtocol {
    init(someParameter: Int)
}

Class Implementations of Protocol Initializer Requirements 协议构造器要求的类实现

You can implement a protocol initializer requirement on a conforming class as either a designated initializer or a convenience initializer. In both cases, you must mark the initializer implementation with the required modifier:

你可以在遵循协议的类中实现构造器,无论是作为指定构造器,还是作为便利构造器。无论哪种情况,你都必须为构造器实现标上 required 修饰符:

class SomeClass: SomeProtocol {
    required init(someParameter: Int) {
        // initializer implementation goes here
    }
}

The use of the required modifier ensures that you provide an explicit or inherited implementation of the initializer requirement on all subclasses of the conforming class, such that they also conform to the protocol.

使用 required 修饰符可以确保所有子类也必须提供此构造器实现,从而也能遵循协议。

For more information on required initializers, see Required Initializers.

关于 required 构造器的更多内容,参考 必要构造器。

Note · 注意

You don't need to mark protocol initializer implementations with the required modifier on classes that are marked with the final modifier, because final classes can't be subclassed. For more about the final modifier, see Preventing Overrides.

如果类已经被标记为 final,那么不需要在协议构造器的实现中使用 required 修饰符,因为 final 类不能有子类。关于 final 修饰符的更多内容,参见 防止重写。

If a subclass overrides a designated initializer from a superclass, and also implements a matching initializer requirement from a protocol, mark the initializer implementation with both the required and override modifiers:

如果一个子类重写了父类的指定构造器,并且该构造器满足了某个协议的构造器要求,那么该构造器的实现需要同时标注 required 和 override 修饰符:

protocol SomeProtocol {
    init()
}

class SomeSuperClass {
    init() {
        // initializer implementation goes here
    }
}

class SomeSubClass: SomeSuperClass, SomeProtocol {
    // "required" from SomeProtocol conformance; "override" from SomeSuperClass
    required override init() {
        // initializer implementation goes here
    }
}

Failable Initializer Requirements 可失败构造器要求

Protocols can define failable initializer requirements for conforming types, as defined in Failable Initializers.

协议还可以为遵循协议的类型定义可失败构造器要求,详见 可失败构造器。

A failable initializer requirement can be satisfied by a failable or nonfailable initializer on a conforming type. A nonfailable initializer requirement can be satisfied by a nonfailable initializer or an implicitly unwrapped failable initializer.

遵循协议的类型可以通过可失败构造器(init?)或非可失败构造器(init)来满足协议中定义的可失败构造器要求。协议中定义的非可失败构造器要求可以通过非可失败构造器(init)或隐式解包可失败构造器(init!)来满足。

Protocols that Have Only Semantic Requirements 仅有语义要求的协议

All of the example protocols above require some methods or properties, but a protocol declaration doesn't have to include any requirements. You can also use a protocol to describe semantic requirements --- that is, requirements about how values of those types behave and about operations that they support.

上面的所有示例协议都要求一些方法或属性,但协议声明不一定要包含任何要求。你还可以使用协议来描述语义要求——也就是关于这些类型的值如何行为以及它们支持哪些操作的要求。

The Swift standard library defines several protocols that don't have any required methods or properties:

Swift 标准库定义了几个不包含任何必需方法或属性的协议:

For information about these protocols' requirements, see the overview in their documentation.

有关这些协议要求的信息,请参阅其文档中的概述。

You use the same syntax to adopt these protocols as you do to adopt other protocols. The only difference is that you don't include method or property declarations that implement the protocol's requirements. For example:

你可以使用与遵循其他协议相同的语法来遵循这些协议。唯一的区别是你不需要包含实现协议要求的方法或属性声明。例如:

struct MyStruct: Copyable {
    var counter = 12
}

extension MyStruct: BitwiseCopyable { }

The code above defines a new structure. Because Copyable has only semantic requirements, there isn't any code in the structure declaration to adopt the protocol. Similarly, because BitwiseCopyable has only semantic requirements, the extension that adopts that protocol has an empty body.

上面的代码定义了一个新的结构体。由于 Copyable 只有语义要求,因此结构体声明中不需要任何代码来遵循该协议。类似地,由于 BitwiseCopyable 只有语义要求,遵循该协议的扩展主体为空。

You usually don't need to write conformance to these protocols --- instead, Swift implicitly adds the conformance for you, as described in Implicit Conformance to a Protocol.

你通常不需要编写对这些协议的遵循——相反,Swift 会隐式地为你添加遵循,如 对协议的隐式遵循 中所述。

Protocols as Types 协议作为类型

Protocols don't actually implement any functionality themselves. Regardless, you can use a protocol as a type in your code.

协议本身并不实现任何功能。尽管如此,你仍然可以在代码中将协议用作类型。

The most common way to use a protocol as a type is to use a protocol as a generic constraint. Code with generic constraints can work with any type that conforms to the protocol, and the specific type is chosen by the code that uses the API. For example, when you call a function that takes an argument and that argument's type is generic, the caller chooses the type.

最常见的将协议用作类型的方式是将其用作泛型约束。具有泛型约束的代码可以与任何符合该协议的类型一起工作,具体的类型由使用该 API 的代码选择。例如,当你调用一个函数并传入一个参数,而该参数的类型是泛型时,调用者会选择具体的类型。

Code with an opaque type works with some type that conforms to the protocol. The underlying type is known at compile time, and the API implementation chooses that type, but that type's identity is hidden from clients of the API. Using an opaque type lets you prevent implementation details of an API from leaking through the layer of abstraction --- for example, by hiding the specific return type from a function, and only guaranteeing that the value conforms to a given protocol.

在代码中使用不透明类型时,可以与某个符合该协议的类型一起工作。底层类型在编译时是已知的,API 实现会选择该类型,但该类型的身份对 API 的使用方是隐藏的。使用不透明类型可以防止 API 的实现细节泄露到抽象层之外 —— 例如,通过隐藏函数的具体返回类型,并仅保证该值符合给定的协议。

Code with a boxed protocol type works with any type, chosen at runtime, that conforms to the protocol. To support this runtime flexibility, Swift adds a level of indirection when necessary --- known as a box, which has a performance cost. Because of this flexibility, Swift doesn't know the underlying type at compile time, which means you can access only the members that are required by the protocol. Accessing any other APIs on the underlying type requires casting at runtime.

代码使用装箱(boxed)的协议类型时,可以与任何在运行时选择的、符合该协议的类型一起工作。为了支持这种运行时的灵活性,Swift 在必要时会添加一个间接层 —— 称为 箱子(box),这会带来性能开销。由于这种灵活性,Swift 在编译时无法知道底层类型,这意味着你只能访问协议所要求的成员。要访问底层类型的任何其他 API,都需要在运行时进行类型转换。

For information about using protocols as generic constraints, see Generics. For information about opaque types, and boxed protocol types, see Opaque and Boxed Protocol Types.

关于使用协议作为泛型约束的信息,参考 泛型。关于不透明类型和封装协议类型的信息,参考 不透明类型和封装协议类型。

Delegation 代理

Delegation is a design pattern that enables a class or structure to hand off (or delegate) some of its responsibilities to an instance of another type. This design pattern is implemented by defining a protocol that encapsulates the delegated responsibilities, such that a conforming type (known as a delegate) is guaranteed to provide the functionality that has been delegated. Delegation can be used to respond to a particular action, or to retrieve data from an external source without needing to know the underlying type of that source.

代理(Delegate) 是一种设计模式,它允许类或结构体将一些需要它们负责的功能代理给其他类型的实例。代理模式的实现很简单:定义协议来封装那些需要被代理的功能,这样就能确保遵循协议的类型能提供这些功能。代理模式可以用来响应特定的动作,或者接收外部数据源提供的数据,而无需关心外部数据源的类型。

The example below defines a dice game and a nested protocol for a delegate that tracks the game's progress:

下面的例子定义了两个基于骰子游戏的协议: 以下示例定义了一个骰子游戏,以及一个用于跟踪游戏进度的嵌套协议:

class DiceGame {
    let sides: Int
    let generator = LinearCongruentialGenerator()
    weak var delegate: Delegate?

    init(sides: Int) {
        self.sides = sides
    }

    func roll() -> Int {
        return Int(generator.random() * Double(sides)) + 1
    }

    func play(rounds: Int) {
        delegate?.gameDidStart(self)
        for round in 1...rounds {
            let player1 = roll()
            let player2 = roll()
            if player1 == player2 {
                delegate?.game(self, didEndRound: round, winner: nil)
            } else if player1 > player2 {
                delegate?.game(self, didEndRound: round, winner: 1)
            } else {
                delegate?.game(self, didEndRound: round, winner: 2)
            }
        }
        delegate?.gameDidEnd(self)
    }

    protocol Delegate: AnyObject {
        func gameDidStart(_ game: DiceGame)
        func game(_ game: DiceGame, didEndRound round: Int, winner: Int?)
        func gameDidEnd(_ game: DiceGame)
    }
}

The DiceGame class implements a game where each player takes a turn rolling dice, and the player who rolls the highest number wins the round. It uses a linear congruential generator from the example earlier in the chapter, to generate random numbers for dice rolls.

DiceGame 类实现了一个游戏,每个玩家轮流掷骰子,掷出最高点数的玩家赢得该轮。它使用前文中示例中的线性同余生成器来生成骰子掷出的随机数。

The DiceGame.Delegate protocol can be adopted to track the progress of a dice game. Because the DiceGame.Delegate protocol is always used in the context of a dice game, it's nested inside of the DiceGame class. Protocols can be nested inside of type declarations like structures and classes, as long as the outer declaration isn't generic. For information about nesting types, see Nested Types.

DiceGame.Delegate 协议可用于跟踪骰子游戏的进度。由于 DiceGame.Delegate 协议总是在骰子游戏的上下文中使用,因此它被嵌套在 DiceGame 类内部。协议可以嵌套在类型声明(如结构体和类)内部,只要外部声明不是泛型。关于嵌套类型的更多信息,参见 嵌套类型。

To prevent strong reference cycles, delegates are declared as weak references. For information about weak references, see Strong Reference Cycles Between Class Instances. Marking the protocol as class-only lets the DiceGame class declare that its delegate must use a weak reference. A class-only protocol is marked by its inheritance from AnyObject, as discussed in Class-Only Protocols.

为了防止强引用循环,代理被声明为弱引用。关于弱引用的更多信息,参见 类实例之间的强引用循环。将协议标记为 class-only 允许 DiceGame 类声明其代理必须使用弱引用。一个 class-only 协议通过继承自 AnyObject 来标记,如 类专属的协议 中所述。

DiceGame.Delegate provides three methods for tracking the progress of a game. These three methods are incorporated into the game logic in the play(rounds:) method above. The DiceGame class calls its delegate methods when a new game starts, a new turn begins, or the game ends.

DiceGame.Delegate 提供了三个方法来跟踪游戏的进度。这三个方法被整合到上面的 play(rounds:) 方法的游戏逻辑中。当新游戏开始、新回合开始或游戏结束时,DiceGame 类会调用它的代理方法。

Because the delegate property is an optional DiceGame.Delegate, the play(rounds:) method uses optional chaining each time it calls a method on the delegate, as discussed in Optional Chaining. If the delegate property is nil, these delegate calls are ignored. If the delegate property is non-nil, the delegate methods are called, and are passed the DiceGame instance as a parameter.

因为 delegate 属性是 可选的 DiceGame.Delegate,所以 play(rounds:) 方法在每次调用代理方法时都使用可选链,如 可选链式调用(Optional Chaining) 中所述。如果 delegate 属性为 nil,这些代理调用将被忽略。如果 delegate 属性不为 nil,则会调用代理方法,并将 DiceGame 实例作为参数传递。

This next example shows a class called DiceGameTracker, which adopts the DiceGame.Delegate protocol:

下一个示例展示了一个名为 DiceGameTracker 的类,它遵循了 DiceGame.Delegate 协议:

class DiceGameTracker: DiceGame.Delegate {
    var playerScore1 = 0
    var playerScore2 = 0
    func gameDidStart(_ game: DiceGame) {
        print("Started a new game")
        playerScore1 = 0
        playerScore2 = 0
    }
    func game(_ game: DiceGame, didEndRound round: Int, winner: Int?) {
        switch winner {
            case 1:
                playerScore1 += 1
                print("Player 1 won round \(round)")
            case 2: playerScore2 += 1
                print("Player 2 won round \(round)")
            default:
                print("The round was a draw")
        }
    }
    func gameDidEnd(_ game: DiceGame) {
        if playerScore1 == playerScore2 {
            print("The game ended in a draw.")
        } else if playerScore1 > playerScore2 {
            print("Player 1 won!")
        } else {
            print("Player 2 won!")
        }
    }
}

The DiceGameTracker class implements all three methods that are required by the DiceGame.Delegate protocol. It uses these methods to zero out both players' scores at the start of a new game, to update their scores at the end of each round, and to announce a winner at the end of the game.

DiceGameTracker 类实现了 DiceGame.Delegate 协议要求的所有三个方法。它通过这些方法在新游戏开始时将两个玩家的分数清零,在每轮结束时更新他们的分数,以及在游戏结束时宣布获胜者。

Here's how DiceGame and DiceGameTracker look in action:

以下是 DiceGame 和 DiceGameTracker 的实际运行情况:

let tracker = DiceGameTracker()
let game = DiceGame(sides: 6)
game.delegate = tracker
game.play(rounds: 3)
// Started a new game
// Player 2 won round 1
// Player 2 won round 2
// Player 1 won round 3
// Player 2 won!

Adding Protocol Conformance with an Extension 在扩展里添加协议遵循

You can extend an existing type to adopt and conform to a new protocol, even if you don't have access to the source code for the existing type. Extensions can add new properties, methods, and subscripts to an existing type, and are therefore able to add any requirements that a protocol may demand. For more about extensions, see Extensions.

即便无法修改源代码,你依然可以通过扩展令已有类型采用并遵循协议。扩展可以为已有类型添加属性、方法、下标以及构造器,因此可以符合协议中可能需要的任意要求。关于扩展的更多详情,参见 扩展。

Note · 注意

Existing instances of a type automatically adopt and conform to a protocol when that conformance is added to the instance's type in an extension.

当一个协议的遵循被添加到实例类型的扩展中时,现有的实例会自动采用并遵循该协议。

For example, this protocol, called TextRepresentable, can be implemented by any type that has a way to be represented as text. This might be a description of itself, or a text version of its current state:

例如下面这个 TextRepresentable 协议,任何想要通过文本表示一些内容的类型都可以实现该协议。这些想要表示的内容可以是实例本身的描述,也可以是实例当前状态的文本描述:

protocol TextRepresentable {
    var textualDescription: String { get }
}

The Dice class from above can be extended to adopt and conform to TextRepresentable:

上面提到的 Dice 类可以被扩展以采用并遵循 TextRepresentable 协议:

extension Dice: TextRepresentable {
    var textualDescription: String {
        return "A \(sides)-sided dice"
    }
}

This extension adopts the new protocol in exactly the same way as if Dice had provided it in its original implementation. The protocol name is provided after the type name, separated by a colon, and an implementation of all requirements of the protocol is provided within the extension's curly braces.

这个扩展遵循新协议的方式,与 Dice 在原始实现中遵循协议的效果完全相同。协议名称写在类型名之后,以冒号隔开,然后在扩展的大括号内实现协议的所有要求。

Any Dice instance can now be treated as TextRepresentable:

现在所有 Dice 的实例都可以被看做 TextRepresentable 类型:

let d12 = Dice(sides: 12, generator: LinearCongruentialGenerator())
print(d12.textualDescription)
// Prints "A 12-sided dice".

Similarly, the SnakesAndLadders game class can be extended to adopt and conform to the TextRepresentable protocol:

同样,SnakesAndLadders 类也可以通过扩展来适配和遵循 TextRepresentable 协议:

extension SnakesAndLadders: TextRepresentable {
    var textualDescription: String {
        return "A game of Snakes and Ladders with \(finalSquare) squares"
    }
}
print(game.textualDescription)
// Prints "A game of Snakes and Ladders with 25 squares".

Conditionally Conforming to a Protocol 有条件地遵循协议

A generic type may be able to satisfy the requirements of a protocol only under certain conditions, such as when the type's generic parameter conforms to the protocol. You can make a generic type conditionally conform to a protocol by listing constraints when extending the type. Write these constraints after the name of the protocol you're adopting by writing a generic where clause. For more about generic where clauses, see Generic Where Clauses.

泛型类型可能只在某些情况下满足一个协议的要求,比如当类型的泛型形式参数遵循对应协议时。你可以通过在扩展类型时列出限制让泛型类型有条件地遵循某协议。在你采用协议的名字后面写泛型 where 分句。更多关于泛型 where 分句,参见 泛型 Where 语句。

The following extension makes Array instances conform to the TextRepresentable protocol whenever they store elements of a type that conforms to TextRepresentable.

下面的扩展让 Array 类型只要在存储遵循 TextRepresentable 协议的元素时,就遵循 TextRepresentable 协议。

extension Array: TextRepresentable where Element: TextRepresentable {
    var textualDescription: String {
        let itemsAsText = self.map { $0.textualDescription }
        return "[" + itemsAsText.joined(separator: ", ") + "]"
    }
}
let myDice = [d6, d12]
print(myDice.textualDescription)
// Prints "[A 6-sided dice, A 12-sided dice]".

Declaring Protocol Adoption with an Extension 在扩展里声明协议遵循

If a type already conforms to all of the requirements of a protocol, but hasn't yet stated that it adopts that protocol, you can make it adopt the protocol with an empty extension:

当一个类型已经遵循了某个协议中的所有要求,却还没有声明遵循该协议时,可以通过空的扩展来让它遵循该协议:

struct Hamster {
    var name: String
    var textualDescription: String {
        return "A hamster named \(name)"
    }
}
extension Hamster: TextRepresentable {}

Instances of Hamster can now be used wherever TextRepresentable is the required type:

从现在起,Hamster 的实例可以作为 TextRepresentable 类型使用:

let simonTheHamster = Hamster(name: "Simon")
let somethingTextRepresentable: TextRepresentable = simonTheHamster
print(somethingTextRepresentable.textualDescription)
// Prints "A hamster named Simon".

Note · 注意

Types don't automatically adopt a protocol just by satisfying its requirements. They must always explicitly declare their adoption of the protocol.

即使满足了协议的所有要求,类型也不会自动遵循协议,必须显式地遵循协议。

Adopting a Protocol Using a Synthesized Implementation 使用合成实现来遵循协议

Swift can automatically provide the protocol conformance for Equatable, Hashable, and Comparable in many simple cases. Using this synthesized implementation means you don't have to write repetitive boilerplate code to implement the protocol requirements yourself.

Swift 可以在很多简单场景下自动提供遵循 Equatable、Hashable 和 Comparable 协议的实现。在使用这些合成实现之后,无需再编写重复的样板代码来实现这些协议所要求的方法。

Swift provides a synthesized implementation of Equatable for the following kinds of custom types:

Swift 为以下几种自定义类型提供了 Equatable 协议的合成实现:

  • Structures that have only stored properties that conform to the Equatable protocol
  • Enumerations that have only associated types that conform to the Equatable protocol
  • Enumerations that have no associated types
  • 只包含遵循 Equatable 协议的存储属性的结构体
  • 只包含遵循 Equatable 协议的关联类型的枚举
  • 没有任何关联类型的枚举

To receive a synthesized implementation of ==, declare conformance to Equatable in the file that contains the original declaration, without implementing an == operator yourself. The Equatable protocol provides a default implementation of !=.

在包含类型原始声明的文件中声明对 Equatable 协议的遵循,可以得到 == 操作符的合成实现,且无需自己编写任何关于 == 的实现代码。Equatable 协议同时包含 != 操作符的默认实现。

The example below defines a Vector3D structure for a three-dimensional position vector (x, y, z), similar to the Vector2D structure. Because the x, y, and z properties are all of an Equatable type, Vector3D receives synthesized implementations of the equivalence operators.

下面的例子中定义了一个 Vector3D 结构体来表示一个类似 Vector2D 的三维向量 (x, y, z)。由于 x、y 和 z 都是满足 Equatable 的类型,Vector3D 可以得到等价运算符的合成实现。

struct Vector3D: Equatable {
    var x = 0.0, y = 0.0, z = 0.0
}

let twoThreeFour = Vector3D(x: 2.0, y: 3.0, z: 4.0)
let anotherTwoThreeFour = Vector3D(x: 2.0, y: 3.0, z: 4.0)
if twoThreeFour == anotherTwoThreeFour {
    print("These two vectors are also equivalent.")
}
// Prints "These two vectors are also equivalent."

Swift provides a synthesized implementation of Hashable for the following kinds of custom types:

Swift 为以下几种自定义类型提供了 Hashable 协议的合成实现:

  • Structures that have only stored properties that conform to the Hashable protocol
  • Enumerations that have only associated types that conform to the Hashable protocol
  • Enumerations that have no associated types
  • 只包含遵循 Hashable 协议的存储属性的结构体
  • 只包含遵循 Hashable 协议的关联类型的枚举
  • 没有任何关联类型的枚举

To receive a synthesized implementation of hash(into:), declare conformance to Hashable in the file that contains the original declaration, without implementing a hash(into:) method yourself.

在包含类型原始声明的文件中声明对 Hashable 协议的遵循,可以得到 hash(into:) 的合成实现,且无需自己编写任何关于 hash(into:) 的实现代码。

Swift provides a synthesized implementation of Comparable for enumerations that don't have a raw value. If the enumeration has associated types, they must all conform to the Comparable protocol. To receive a synthesized implementation of <, declare conformance to Comparable in the file that contains the original enumeration declaration, without implementing a < operator yourself. The Comparable protocol's default implementation of <=, >, and >= provides the remaining comparison operators.

Swift 为没有原始值的枚举类型提供了 Comparable 协议的合成实现。如果枚举类型包含关联类型,那这些关联类型也必须同时遵循 Comparable 协议。在包含原始枚举类型声明的文件中声明其对 Comparable 协议的遵循,可以得到 < 操作符的合成实现,且无需自己编写任何关于 < 的实现代码。Comparable 协议同时包含 <=、> 和 >= 操作符的默认实现。

The example below defines a SkillLevel enumeration with cases for beginners, intermediates, and experts. Experts are additionally ranked by the number of stars they have.

下面的例子中定义了 SkillLevel 枚举类型,其中定义了 beginner(初学者)、intermediate(中级)和 expert(专家)三种类型,专家类型会由额外的 stars(星级)数量来进行排名。

enum SkillLevel: Comparable {
    case beginner
    case intermediate
    case expert(stars: Int)
}
var levels = [SkillLevel.intermediate, SkillLevel.beginner,
              SkillLevel.expert(stars: 5), SkillLevel.expert(stars: 3)]
for level in levels.sorted() {
    print(level)
}
// Prints "beginner".
// Prints "intermediate".
// Prints "expert(stars: 3)".
// Prints "expert(stars: 5)".

Implicit Conformance to a Protocol 对协议的隐式遵循

Some protocols are so common that you would write them almost every time you declare a new type. For the following protocols, Swift automatically infers the conformance when you define a type that implements the protocol's requirements, so you don't have to write them yourself:

有些协议非常常见,以至于你几乎在每次声明新类型时都会编写它们。对于以下协议,当你定义一个实现协议要求的类型时,Swift 会自动推断其遵循性,因此你不必自己编写:

You can still write the conformance explicitly, but it doesn't change how your code behaves. To suppress an implicit conformance, write a tilde (~) before the protocol name in the conformance list:

你仍然可以显式编写遵循声明,但这不会改变代码的行为方式。要抑制隐式遵循,在遵循列表中的协议名称前写一个波浪号(~):

struct FileDescriptor: ~Sendable {
    let rawValue: Int
}

The code above shows part of a wrapper around POSIX file descriptors. The FileDescriptor structure satisfies all of the requirements of the Sendable protocol, which normally makes it sendable. However, writing ~Sendable suppresses this implicit conformance. Even though file descriptors use integers to identify and interact with open files, and integer values are sendable, making it nonsendable can help avoid certain kinds of bugs.

上面的代码显示了 POSIX 文件描述符包装器的一部分。FileDescriptor 结构体满足 Sendable 协议的所有要求,这通常会使其可发送。然而,编写 ~Sendable 会抑制这种隐式遵循。即使文件描述符使用整数来标识和与打开的文件交互,并且整数值是可发送的,使其不可发送可以帮助避免某些类型的错误。

Another way to suppress implicit conformance is with an extension that you mark as unavailable:

抑制隐式遵循的另一种方式是使用标记为不可用的扩展:

@available(*, unavailable)
extension FileDescriptor: Sendable { }

When you write ~Sendable in one place in your code, as in the previous example, code elsewhere in your program can still extend the FileDescriptor type to add Sendable conformance. In contrast, the unavailable extension in this example suppresses the implicit conformance to Sendable and also prevents any extensions elsewhere in your code from adding Sendable conformance to the type.

当你在代码中的某处编写 ~Sendable 时(如前面的示例所示),代码的其他地方仍然可以扩展 FileDescriptor 类型以添加 Sendable 遵循。相反,此示例中的不可用扩展会抑制对 Sendable 的隐式遵循,并且还会阻止代码中其他任何地方的扩展向该类型添加 Sendable 遵循。

Note · 注意

In addition to the protocols discussed above, distributed actors implicitly conform to the Codable protocol.

除了上面讨论的协议之外,分布式 actor 还隐式遵循 Codable 协议。

Collections of Protocol Types 协议类型的集合

A protocol can be used as the type to be stored in a collection such as an array or a dictionary, as mentioned in Protocols as Types. This example creates an array of TextRepresentable things:

协议类型可以在数组或者字典这样的集合中使用,在 协议作为类型 提到了这样的用法。下面的例子创建了一个元素类型为 TextRepresentable 的数组:

let things: [TextRepresentable] = [game, d12, simonTheHamster]

It's now possible to iterate over the items in the array, and print each item's textual description:

现在可以遍历 things 数组,并打印每个元素的文本表示:

for thing in things {
    print(thing.textualDescription)
}
// A game of Snakes and Ladders with 25 squares
// A 12-sided dice
// A hamster named Simon

Note that the thing constant is of type TextRepresentable. It's not of type Dice, or DiceGame, or Hamster, even if the actual instance behind the scenes is of one of those types. Nonetheless, because it's of type TextRepresentable, and anything that's TextRepresentable is known to have a textualDescription property, it's safe to access thing.textualDescription each time through the loop.

注意 thing 常量是 TextRepresentable 类型而不是 Dice,DiceGame,Hamster 等类型,即使实例在幕后确实是这些类型中的一种。由于 thing 是 TextRepresentable 类型,任何 TextRepresentable 的实例都有一个 textualDescription 属性,所以在每次循环中可以安全地访问 thing.textualDescription。

Protocol Inheritance 协议的继承

A protocol can inherit one or more other protocols and can add further requirements on top of the requirements it inherits. The syntax for protocol inheritance is similar to the syntax for class inheritance, but with the option to list multiple inherited protocols, separated by commas:

协议能够 继承(inherit) 一个或多个其他协议,可以在继承的协议的基础上增加新的要求。协议的继承语法与类的继承相似,多个被继承的协议间用逗号分隔:

protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
    // protocol definition goes here
}

Here's an example of a protocol that inherits the TextRepresentable protocol from above:

如下所示,PrettyTextRepresentable 协议继承了上面提到的 TextRepresentable 协议:

protocol PrettyTextRepresentable: TextRepresentable {
    var prettyTextualDescription: String { get }
}

This example defines a new protocol, PrettyTextRepresentable, which inherits from TextRepresentable. Anything that adopts PrettyTextRepresentable must satisfy all of the requirements enforced by TextRepresentable, plus the additional requirements enforced by PrettyTextRepresentable. In this example, PrettyTextRepresentable adds a single requirement to provide a gettable property called prettyTextualDescription that returns a String.

例子中定义了一个新的协议 PrettyTextRepresentable,它继承自 TextRepresentable 协议。任何遵循 PrettyTextRepresentable 协议的类型,除了必须满足 TextRepresentable 协议的要求,还要 额外满足 PrettyTextRepresentable 协议的要求。在这个例子中,PrettyTextRepresentable 协议额外要求遵循协议的类型提供一个返回值为 String 类型的 prettyTextualDescription 属性。

The SnakesAndLadders class can be extended to adopt and conform to PrettyTextRepresentable:

如下所示,扩展 SnakesAndLadders,使其采用并遵循 PrettyTextRepresentable 协议:

extension SnakesAndLadders: PrettyTextRepresentable {
    var prettyTextualDescription: String {
        var output = textualDescription + ":\n"
        for index in 1...finalSquare {
            switch board[index] {
            case let ladder where ladder > 0:
                output += "▲ "
            case let snake where snake < 0:
                output += "▼ "
            default:
                output += "○ "
            }
        }
        return output
    }
}

This extension states that it adopts the PrettyTextRepresentable protocol and provides an implementation of the prettyTextualDescription property for the SnakesAndLadders type. Anything that's PrettyTextRepresentable must also be TextRepresentable, and so the implementation of prettyTextualDescription starts by accessing the textualDescription property from the TextRepresentable protocol to begin an output string. It appends a colon and a line break, and uses this as the start of its pretty text representation. It then iterates through the array of board squares, and appends a geometric shape to represent the contents of each square:

上述扩展令 SnakesAndLadders 遵循了 PrettyTextRepresentable 协议,并提供了协议要求的 prettyTextualDescription 属性。每个 PrettyTextRepresentable 类型同时也是 TextRepresentable 类型,所以在 prettyTextualDescription 的实现中,可以访问 textualDescription 属性,然后拼接上冒号和换行符,接着遍历数组中的元素,拼接一个几何图形来表示每个棋盘方格的内容:

  • If the square's value is greater than 0, it's the base of a ladder, and is represented by ▲.
  • If the square's value is less than 0, it's the head of a snake, and is represented by ▼.
  • Otherwise, the square's value is 0, and it's a “free” square, represented by ○.
  • 当从数组中取出的元素的值大于 0 时,用 ▲ 表示。
  • 当从数组中取出的元素的值小于 0 时,用 ▼ 表示。
  • 当从数组中取出的元素的值等于 0 时,用 ○ 表示。

The prettyTextualDescription property can now be used to print a pretty text description of any SnakesAndLadders instance:

现在可以使用 prettyTextualDescription 属性来打印任意 SnakesAndLadders 实例的漂亮文本描述:

print(game.prettyTextualDescription)
// A game of Snakes and Ladders with 25 squares:
// ○ ○ ▲ ○ ○ ▲ ○ ○ ▲ ▲ ○ ○ ○ ▼ ○ ○ ○ ○ ▼ ○ ○ ▼ ○ ▼ ○

Class-Only Protocols 类专属的协议

You can limit protocol adoption to class types (and not structures or enumerations) by adding the AnyObject protocol to a protocol's inheritance list.

你通过添加 AnyObject 关键字到协议的继承列表,就可以限制协议只能被类类型遵循(而不能是结构体类型或者枚举类型)。

protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol {
    // class-only protocol definition goes here
}

In the example above, SomeClassOnlyProtocol can only be adopted by class types. It's a compile-time error to write a structure or enumeration definition that tries to adopt SomeClassOnlyProtocol.

在以上例子中,协议 SomeClassOnlyProtocol 只能被类类型遵循。如果尝试让结构体或枚举类型遵循 SomeClassOnlyProtocol,则会导致编译时错误。

Note · 注意

Use a class-only protocol when the behavior defined by that protocol's requirements assumes or requires that a conforming type has reference semantics rather than value semantics. For more about reference and value semantics, see Structures and Enumerations Are Value Types and Classes Are Reference Types.

当协议定义的要求需要遵循协议的类型必须是引用语义而非值语义时,应该使用类类型专属协议。关于引用语义和值语义的更多内容,参见 结构体和枚举是值类型 和 类是引用类型。

You can also name a specific class in a protocol's inheritance list to require that all conforming types are subclasses of that class.

你也可以在协议的继承列表中指定一个具体的类,以要求所有遵循该协议的类型都是这个类的子类。

class Renderer {
    func render(_ text: String) {
        print(text)
    }
}

protocol Widget: Renderer {
    var title: String { get }
}

extension Widget {
    func display() {
        render(title)
    }
}

class ButtonWidget: Renderer, Widget {
    var title: String
    init(title: String) {
        self.title = title
    }
}

let button = ButtonWidget(title: "OK")
button.display()
// Prints "OK".

In the example above, Widget can only be adopted by subclasses of Renderer. Because the protocol guarantees that every conforming type is a Renderer subclass, the Widget protocol extension can call render(_:) directly. A superclass requirement is more restrictive than using AnyObject: it limits conformance to a specific class hierarchy, not just any class type. Use this when the protocol's implementation depends on the concrete behavior of a particular base class.

在上面的例子中,Widget 只能被 Renderer 的子类采纳。因为协议保证了每个遵循它的类型都是 Renderer 的子类,所以 Widget 的协议扩展可以直接调用 render(_:)。父类要求比使用 AnyObject 的限制更严格:它把遵循限定在一个特定的类层次结构中,而不仅仅是任意类类型。当协议的实现依赖于某个特定基类的具体行为时,就使用这种方式。

Protocol Composition 协议组合

It can be useful to require a type to conform to multiple protocols at the same time. You can combine multiple protocols into a single requirement with a protocol composition. Protocol compositions behave as if you defined a temporary local protocol that has the combined requirements of all protocols in the composition. Protocol compositions don't define any new protocol types.

要求一个类型同时遵循多个协议是很有用的。你可以使用 协议组合 来组合多个协议到一个要求里。协议组合的行为就和你定义的临时局部协议一样,拥有组合中所有协议的需求。协议组合不定义任何新的协议类型。

Protocol compositions have the form SomeProtocol & AnotherProtocol. You can list as many protocols as you need, separating them with ampersands (&). In addition to its list of protocols, a protocol composition can also contain one class type, which you can use to specify a required superclass.

协议组合使用 SomeProtocol & AnotherProtocol 的形式。你可以列举任意数量的协议,用和符号(&)分开。除了协议列表,协议组合也能包含类类型,这允许你标明一个需要的父类。

Here's an example that combines two protocols called Named and Aged into a single protocol composition requirement on a function parameter:

下面的例子中,将 Named 和 Aged 两个协议按照上述语法组合成一个协议,作为函数参数的类型:

protocol Named {
    var name: String { get }
}
protocol Aged {
    var age: Int { get }
}
struct Person: Named, Aged {
    var name: String
    var age: Int
}
func wishHappyBirthday(to celebrator: Named & Aged) {
    print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!")
}
let birthdayPerson = Person(name: "Malcolm", age: 21)
wishHappyBirthday(to: birthdayPerson)
// Prints "Happy birthday, Malcolm, you're 21!"

In this example, the Named protocol has a single requirement for a gettable String property called name. The Aged protocol has a single requirement for a gettable Int property called age. Both protocols are adopted by a structure called Person.

在这个例子中,Named 协议包含 String 类型的 name 属性。Aged 协议包含 Int 类型的 age 属性。Person 结构体遵循了这两个协议。

The example also defines a wishHappyBirthday(to:) function. The type of the celebrator parameter is Named & Aged, which means “any type that conforms to both the Named and Aged protocols.” It doesn't matter which specific type is passed to the function, as long as it conforms to both of the required protocols.

这个例子中也定义了一个 wishHappyBirthday(to:) 函数,其形参 celebrator 的类型为 Named & Aged,这意味着“任何同时遵循 Named 和 Aged 协议的类型”。它不关心传入函数的具体类型,只要该类型遵循这两个协议即可。

The example then creates a new Person instance called birthdayPerson and passes this new instance to the wishHappyBirthday(to:) function. Because Person conforms to both protocols, this call is valid, and the wishHappyBirthday(to:) function can print its birthday greeting.

这个例子随后创建了一个名为 birthdayPerson 的 Person 的实例,作为参数传递给了 wishHappyBirthday(to:) 函数。因为 Person 同时遵循这两个协议,所以这个参数合法,wishHappyBirthday(to:) 函数就能打印生日问候语。

Here's an example that combines the Named protocol from the previous example with a Location class:

这里有一个例子:将 Location 类和前面的 Named 协议进行组合:

class Location {
    var latitude: Double
    var longitude: Double
    init(latitude: Double, longitude: Double) {
        self.latitude = latitude
        self.longitude = longitude
    }
}
class City: Location, Named {
    var name: String
    init(name: String, latitude: Double, longitude: Double) {
        self.name = name
        super.init(latitude: latitude, longitude: longitude)
    }
}
func beginConcert(in location: Location & Named) {
    print("Hello, \(location.name)!")
}

let seattle = City(name: "Seattle", latitude: 47.6, longitude: -122.3)
beginConcert(in: seattle)
// Prints "Hello, Seattle!"

The beginConcert(in:) function takes a parameter of type Location & Named, which means "any type that's a subclass of Location and that conforms to the Named protocol." In this case, City satisfies both requirements.

beginConcert(in:) 函数接受一个类型为 Location & Named 的参数,这意味着“任何 Location 的子类,并且遵循 Named 协议”。在这个例子中,City 就满足这样的条件。

Passing birthdayPerson to the beginConcert(in:) function is invalid because Person isn't a subclass of Location. Likewise, if you made a subclass of Location that didn't conform to the Named protocol, calling beginConcert(in:) with an instance of that type is also invalid.

将 birthdayPerson 传入 beginConcert(in:) 函数是不合法的,因为 Person 不是 Location 的子类。同理,如果你新建一个类继承于 Location,但是没有遵循 Named 协议,用这个类的实例去调用 beginConcert(in:) 函数也是不合法的。

Checking for Protocol Conformance 检查是否遵循协议

You can use the is and as operators described in Type Casting to check for protocol conformance, and to cast to a specific protocol. Checking for and casting to a protocol follows exactly the same syntax as checking for and casting to a type:

你可以使用 类型转换 中描述的 is 和 as 操作符来检查是否遵循某协议,并且可以类型转换到指定的协议。检查和转换协议的语法与检查和转换类型是完全一样的:

  • The is operator returns true if an instance conforms to a protocol and returns false if it doesn't.
  • The as? version of the downcast operator returns an optional value of the protocol's type, and this value is nil if the instance doesn't conform to that protocol.
  • The as! version of the downcast operator forces the downcast to the protocol type and triggers a runtime error if the downcast doesn't succeed.
  • is 用来检查实例是否遵循某个协议,若遵循则返回 true,否则返回 false。
  • as? 返回一个可选值,当实例遵循某个协议时,返回类型为协议类型的可选值,否则返回 nil。
  • as! 将实例强制向下转换到某个协议类型,如果强转失败,将触发运行时错误。

This example defines a protocol called HasArea, with a single property requirement of a gettable Double property called area:

下面的例子定义了一个 HasArea 协议,该协议定义了一个 Double 类型的可读属性 area:

protocol HasArea {
    var area: Double { get }
}

Here are two classes, Circle and Country, both of which conform to the HasArea protocol:

如下所示,Circle 类和 Country 类都遵循了 HasArea 协议:

class Circle: HasArea {
    let pi = 3.1415927
    var radius: Double
    var area: Double { return pi * radius * radius }
    init(radius: Double) { self.radius = radius }
}
class Country: HasArea {
    var area: Double
    init(area: Double) { self.area = area }
}

The Circle class implements the area property requirement as a computed property, based on a stored radius property. The Country class implements the area requirement directly as a stored property. Both classes correctly conform to the HasArea protocol.

Circle 类把 area 属性实现为基于存储型属性 radius 的计算型属性。Country 类则把 area 属性实现为存储型属性。这两个类都正确地遵循了 HasArea 协议。

Here's a class called Animal, which doesn't conform to the HasArea protocol:

如下所示,Animal 是一个未遵循 HasArea 协议的类:

class Animal {
    var legs: Int
    init(legs: Int) { self.legs = legs }
}

The Circle, Country and Animal classes don't have a shared base class. Nonetheless, they're all classes, and so instances of all three types can be used to initialize an array that stores values of type AnyObject:

Circle,Country,Animal 并没有一个共同的基类,尽管如此,它们都是类,它们的实例都可以作为 AnyObject 类型的值,存储在同一个数组中:

let objects: [AnyObject] = [
    Circle(radius: 2.0),
    Country(area: 243_610),
    Animal(legs: 4)
]

The objects array is initialized with an array literal containing a Circle instance with a radius of 2 units; a Country instance initialized with the surface area of the United Kingdom in square kilometers; and an Animal instance with four legs.

objects 数组使用字面量初始化,数组包含一个 radius 为 2 的 Circle 的实例,一个保存了英国国土面积的 Country 实例和一个 legs 为 4 的 Animal 实例。

The objects array can now be iterated, and each object in the array can be checked to see if it conforms to the HasArea protocol:

如下所示,objects 数组可以被迭代,并对迭代出的每一个元素进行检查,看它是否遵循 HasArea 协议:

for object in objects {
    if let objectWithArea = object as? HasArea {
        print("Area is \(objectWithArea.area)")
    } else {
        print("Something that doesn't have an area")
    }
}
// Area is 12.5663708
// Area is 243610.0
// Something that doesn't have an area

Whenever an object in the array conforms to the HasArea protocol, the optional value returned by the as? operator is unwrapped with optional binding into a constant called objectWithArea. The objectWithArea constant is known to be of type HasArea, and so its area property can be accessed and printed in a type-safe way.

当迭代出的元素遵循 HasArea 协议时,将 as? 操作符返回的可选值通过可选绑定,绑定到 objectWithArea 常量上。objectWithArea 是 HasArea 协议类型的常量,因此 area 属性可以类型安全地被访问和打印。

Note that the underlying objects aren't changed by the casting process. They continue to be a Circle, a Country and an Animal. However, at the point that they're stored in the objectWithArea constant, they're only known to be of type HasArea, and so only their area property can be accessed.

objects 数组中实际的元素的类型并不会因为强转而丢失类型信息,它们仍然是 Circle,Country,Animal 类型。然而,当它们被赋值给 objectWithArea 常量时,只被视为 HasArea 类型,因此只有 area 属性能够被访问。

Optional Protocol Requirements 可选协议要求

You can define optional requirements for protocols. These requirements don't have to be implemented by types that conform to the protocol. Optional requirements are prefixed by the optional modifier as part of the protocol's definition. Optional requirements are available so that you can write code that interoperates with Objective-C. Both the protocol and the optional requirement must be marked with the @objc attribute. Note that @objc protocols can be adopted only by classes, not by structures or enumerations.

协议可以定义 可选要求(optional requirements),遵循协议的类型可以选择是否实现这些要求。在协议中使用 optional 关键字作为前缀来定义可选要求。可选要求用在你需要和 Objective-C 打交道的代码中。协议和可选要求都必须带上 @objc 属性。注意被标记为 @objc 的协议只能被类遵循,不能被结构体和枚举遵循。

When you use a method or property in an optional requirement, its type automatically becomes an optional. For example, a method of type (Int) -> String becomes ((Int) -> String)?. Note that the entire function type is wrapped in the optional, not the method's return value.

使用可选要求中的方法或者属性时,它们的类型会自动变成可选的。比如,一个类型为 (Int) -> String 的方法会变成 ((Int) -> String)?。需要注意的是整个函数类型是可选的,而不是函数的返回值。

An optional protocol requirement can be called with optional chaining, to account for the possibility that the requirement was not implemented by a type that conforms to the protocol. You check for an implementation of an optional method by writing a question mark after the name of the method when it's called, such as someOptionalMethod?(someArgument). For information on optional chaining, see Optional Chaining.

协议中的可选要求可通过可选链式调用来使用,因为遵循协议的类型可能没有实现这些可选要求。类似 someOptionalMethod?(someArgument) 这样,你可以在可选方法名称后加上 ? 来调用可选方法。和可选链式有关的详细内容,可参见 可选链式调用(Optional Chaining)。

The following example defines an integer-counting class called Counter, which uses an external data source to provide its increment amount. This data source is defined by the CounterDataSource protocol, which has two optional requirements:

下面的例子定义了一个名为 Counter 的用于整数计数的类,它使用外部的数据源来提供每次的增量。数据源由 CounterDataSource 协议定义,它包含两个可选要求:

@objc protocol CounterDataSource {
    @objc optional func increment(forCount count: Int) -> Int
    @objc optional var fixedIncrement: Int { get }
}

The CounterDataSource protocol defines an optional method requirement called increment(forCount:) and an optional property requirement called fixedIncrement. These requirements define two different ways for data sources to provide an appropriate increment amount for a Counter instance.

CounterDataSource 协议定义了一个名为 increment(forCount:) 的可选方法要求和一个名为 fixedIncrement 的可选属性要求。这两个要求定义了数据源为 Counter 实例提供适当增量的两种不同方式。

Note · 注意

Strictly speaking, you can write a custom class that conforms to CounterDataSource without implementing either protocol requirement. They're both optional, after all. Although technically allowed, this wouldn't make for a very good data source.

严格来讲,CounterDataSource 协议中的方法和属性都是可选的,因此遵循协议的类可以不实现这些要求,尽管技术上允许这样做,不过作为一个数据源,最好不要这样写。

The Counter class, defined below, has an optional dataSource property of type CounterDataSource?:

下面定义的 Counter 类含有 CounterDataSource? 类型的可选属性 dataSource,如下所示:

class Counter {
    var count = 0
    var dataSource: CounterDataSource?
    func increment() {
        if let amount = dataSource?.increment?(forCount: count) {
            count += amount
        } else if let amount = dataSource?.fixedIncrement {
            count += amount
        }
    }
}

The Counter class stores its current value in a variable property called count. The Counter class also defines a method called increment, which increments the count property every time the method is called.

Counter 类使用变量属性 count 来存储当前值。该类还定义了一个 increment 方法,每次调用该方法的时候,将会增加 count 的值。

The increment() method first tries to retrieve an increment amount by looking for an implementation of the increment(forCount:) method on its data source. The increment() method uses optional chaining to try to call increment(forCount:), and passes the current count value as the method's single argument.

increment() 方法首先尝试使用其数据源的 increment(forCount:) 方法实现来得到每次的增量。increment() 方法使用可选链式调用来尝试调用 increment(forCount:),并将当前的 count 值作为参数传入。

Note that two levels of optional chaining are at play here. First, it's possible that dataSource may be nil, and so dataSource has a question mark after its name to indicate that increment(forCount:) should be called only if dataSource isn't nil. Second, even if dataSource does exist, there's no guarantee that it implements increment(forCount:), because it's an optional requirement. Here, the possibility that increment(forCount:) might not be implemented is also handled by optional chaining. The call to increment(forCount:) happens only if increment(forCount:) exists --- that is, if it isn't nil. This is why increment(forCount:) is also written with a question mark after its name.

这里使用了 两 层可选链式调用。首先,由于 dataSource 可能为 nil,因此在 dataSource 后边加上了 ?,以此表明只在 dataSource 非空时才去调用 increment(forCount:) 方法。其次,即使 dataSource 确实存在 ,也无法保证其是否实现了 increment(forCount:) 方法,因为这个方法是可选的。在这里,increment(forCount:) 可能没有被实现的可能性,也通过可选链被处理了。只有当 increment(forCount:) 存在时——也就是说,如果它不是 nil ——才会调用 increment(forCount:)。这就是为什么 increment(forCount:) 也在名称后面写有一个问号。

Because the call to increment(forCount:) can fail for either of these two reasons, the call returns an optional Int value. This is true even though increment(forCount:) is defined as returning a non-optional Int value in the definition of CounterDataSource. Even though there are two optional chaining operations, one after another, the result is still wrapped in a single optional. For more information about using multiple optional chaining operations, see Linking Multiple Levels of Chaining.

调用 increment(forCount:) 方法在上述两种情形下都有可能失败,所以返回值为 Int? 可选 类型,即使在 CounterDataSource 协议中,increment(forCount:) 的返回值类型是非可选 Int。另外,即使这里使用了两层可选链式调用,最后的返回结果依旧是单层的可选类型。关于使用多层可选链式调用的更多信息,参见 连接多层可选链式调用。

After calling increment(forCount:), the optional Int that it returns is unwrapped into a constant called amount, using optional binding. If the optional Int does contain a value --- that is, if the delegate and method both exist, and the method returned a value --- the unwrapped amount is added onto the stored count property, and incrementation is complete.

在调用 increment(forCount:) 方法后,可选 Int 型的返回值通过可选绑定解包并赋值给常量 amount。如果可选值确实包含一个数值,也就是说,数据源和方法都存在,并且数据源方法返回了一个有效值,就会将解包后的 amount 加到 count 上,增量操作就完成了。

If it's not possible to retrieve a value from the increment(forCount:) method --- either because dataSource is nil, or because the data source doesn't implement increment(forCount:) --- then the increment() method tries to retrieve a value from the data source's fixedIncrement property instead. The fixedIncrement property is also an optional requirement, so its value is an optional Int value, even though fixedIncrement is defined as a non-optional Int property as part of the CounterDataSource protocol definition.

如果 没有 从 increment(forCount:) 方法获取到值,可能由于 dataSource 为 nil,或者它并没有实现 increment(forCount:) 方法,那么 increment() 方法将试图从数据源的 fixedIncrement 属性中获取增量。fixedIncrement 是一个可选属性,因此属性值是一个可选 Int 值,即使该属性在 CounterDataSource 协议中的类型是非可选的 Int。

Here's a simple CounterDataSource implementation where the data source returns a constant value of 3 every time it's queried. It does this by implementing the optional fixedIncrement property requirement:

下面的例子展示了 CounterDataSource 的简单实现。ThreeSource 类遵循了 CounterDataSource 协议,它实现了可选属性 fixedIncrement,每次会返回 3:

class ThreeSource: NSObject, CounterDataSource {
    let fixedIncrement = 3
}

You can use an instance of ThreeSource as the data source for a new Counter instance:

你可以使用 ThreeSource 的实例作为新 Counter 实例的数据源:

var counter = Counter()
counter.dataSource = ThreeSource()
for _ in 1...4 {
    counter.increment()
    print(counter.count)
}
// 3
// 6
// 9
// 12

The code above creates a new Counter instance; sets its data source to be a new ThreeSource instance; and calls the counter's increment() method four times. As expected, the counter's count property increases by three each time increment() is called.

上述代码新建了一个 Counter 实例,并将它的数据源设置为一个 ThreeSource 的实例,然后调用 increment() 方法 4 次。正如预期一样,每次调用都会将 count 的值增加 3.

Here's a more complex data source called TowardsZeroSource, which makes a Counter instance count up or down towards zero from its current count value:

下面是一个更为复杂的数据源 TowardsZeroSource,它将使得 Counter 实例的 count 属性的值增加或减少,最终变为 0:

class TowardsZeroSource: NSObject, CounterDataSource {
    func increment(forCount count: Int) -> Int {
        if count == 0 {
            return 0
        } else if count < 0 {
            return 1
        } else {
            return -1
        }
    }
}

The TowardsZeroSource class implements the optional increment(forCount:) method from the CounterDataSource protocol and uses the count argument value to work out which direction to count in. If count is already zero, the method returns 0 to indicate that no further counting should take place.

TowardsZeroSource 实现了 CounterDataSource 协议中的 increment(forCount:) 可选方法,以 count 参数为依据,来确定计数的方向。如果 count 已经为 0,此方法将返回 0,以此表明之后不应再有计数操作发生。

You can use an instance of TowardsZeroSource with the existing Counter instance to count from -4 to zero. Once the counter reaches zero, no more counting takes place:

你可以使用一个 TowardsZeroSource 实例将 Counter 实例来从 -4 数到 0。一旦达到 0,数值便不会再有变动:

counter.count = -4
counter.dataSource = TowardsZeroSource()
for _ in 1...5 {
    counter.increment()
    print(counter.count)
}
// -3
// -2
// -1
// 0
// 0

Protocol Extensions 协议扩展

Protocols can be extended to provide method, initializer, subscript, and computed property implementations to conforming types. This allows you to define behavior on protocols themselves, rather than in each type's individual conformance or in a global function.

协议可以通过扩展来为遵循协议的类型提供方法、初始化方法、下标以及计算属性的实现。通过这种方式,你可以基于协议本身来实现这些功能,而无需在每个遵循协议的类型中都重复同样的实现,也无需使用全局函数。

For example, the RandomNumberGenerator protocol can be extended to provide a randomBool() method, which uses the result of the required random() method to return a random Bool value:

例如,可以扩展 RandomNumberGenerator 协议来提供 randomBool() 方法。该方法使用协议中定义的 random() 方法来返回一个随机的 Bool 值:

extension RandomNumberGenerator {
    func randomBool() -> Bool {
        return random() > 0.5
    }
}

By creating an extension on the protocol, all conforming types automatically gain this method implementation without any additional modification.

通过添加协议扩展,所有遵循协议的类型,都能自动获得这个扩展所增加的方法实现,而无需任何额外修改。

let generator = LinearCongruentialGenerator()
print("Here's a random number: \(generator.random())")
// Prints "Here's a random number: 0.3746499199817101".
print("And here's a random Boolean: \(generator.randomBool())")
// Prints "And here's a random Boolean: true".

Protocol extensions can add implementations to conforming types but can't make a protocol extend or inherit from another protocol. Protocol inheritance is always specified in the protocol declaration itself.

协议扩展可以为遵循协议的类型增加实现,但不能声明该协议继承自另一个协议。协议的继承只能在协议声明处进行指定。

Providing Default Implementations 提供默认实现

You can use protocol extensions to provide a default implementation to any method or computed property requirement of that protocol. If a conforming type provides its own implementation of a required method or property, that implementation will be used instead of the one provided by the extension.

你可以通过协议扩展来为协议要求的方法、计算属性提供默认的实现。如果遵循协议的类型为这些要求提供了自己的实现,那么这些自定义实现将会替代扩展中的默认实现被使用。

Note · 注意

Protocol requirements with default implementations provided by extensions are distinct from optional protocol requirements. Although conforming types don't have to provide their own implementation of either, requirements with default implementations can be called without optional chaining.

通过协议扩展为协议要求提供的默认实现和可选的协议要求不同。虽然在这两种情况下,遵循协议的类型都无需自己实现这些要求,但是通过扩展提供的默认实现可以直接调用,而无需使用可选链式调用。

For example, the PrettyTextRepresentable protocol, which inherits the TextRepresentable protocol can provide a default implementation of its required prettyTextualDescription property to simply return the result of accessing the textualDescription property:

例如,PrettyTextRepresentable 协议继承自 TextRepresentable 协议,可以为其提供一个默认的 prettyTextualDescription 属性来简单地返回 textualDescription 属性的值:

extension PrettyTextRepresentable  {
    var prettyTextualDescription: String {
        return textualDescription
    }
}

Adding Constraints to Protocol Extensions 为协议扩展添加限制条件

When you define a protocol extension, you can specify constraints that conforming types must satisfy before the methods and properties of the extension are available. You write these constraints after the name of the protocol you're extending by writing a generic where clause. For more about generic where clauses, see Generic Where Clauses.

在扩展协议的时候,可以指定一些限制条件,只有遵循协议的类型满足这些限制条件时,才能获得协议扩展提供的默认实现。这些限制条件写在协议名之后,使用 where 子句来描述,更多和泛型 where 子句的内容,参见 泛型 Where 语句。

For example, you can define an extension to the Collection protocol that applies to any collection whose elements conform to the Equatable protocol. By constraining a collection's elements to the Equatable protocol, a part of the Swift standard library, you can use the == and != operators to check for equality and inequality between two elements.

例如,你可以扩展 Collection 协议,适用于集合中的元素遵循了 Equatable 协议的情况。通过限制集合元素遵循 Equatable 协议(Swift 标准库的一部分), 你可以使用 == 和 != 操作符来检查两个元素的等价性和非等价性。

extension Collection where Element: Equatable {
    func allEqual() -> Bool {
        for element in self {
            if element != self.first {
                return false
            }
        }
        return true
    }
}

The allEqual() method returns true only if all the elements in the collection are equal.

如果集合中的所有元素都一致,allEqual() 方法才返回 true。

Consider two arrays of integers, one where all the elements are the same, and one where they aren't:

例如两个整数数组,一个数组的所有元素都是一样的,另一个不一样:

let equalNumbers = [100, 100, 100, 100, 100]
let differentNumbers = [100, 100, 200, 100, 200]

Because arrays conform to Collection and integers conform to Equatable, equalNumbers and differentNumbers can use the allEqual() method:

由于数组遵循 Collection 并且整数遵循 Equatable,equalNumbers 和 differentNumbers 都可以使用 allEqual() 方法:

print(equalNumbers.allEqual())
// Prints "true".
print(differentNumbers.allEqual())
// Prints "false".

Note · 注意

If a conforming type satisfies the requirements for multiple constrained extensions that provide implementations for the same method or property, Swift uses the implementation corresponding to the most specialized constraints.

如果一个遵循类型满足了为同一方法或属性提供实现的多个有限制条件的协议扩展的要求,Swift 会使用最贴合限制的实现。

On this page