定义有什么,及哪些必须实现。
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.
Property Requirements
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.
protocol SomeProtocol {
var mustBeSettable: Int { get set }
var doesNotNeedToBeSettable: Int { get }
}
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.
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.
protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol {
// class-only protocol definition goes here
协议联合体作为参量
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)