Swift 协议
在本教程中,我们将通过实例学习 Swift 协议。
在 Swift 中,协议定义了方法或属性的蓝图,然后可以被类(或任何其他类型)采用。
我们使用 protocol 关键字来定义协议。例如,
protocol Greet {// blueprint of a propertyvar name: String { get }// blueprint of a methodfunc message()}
这里,
Greet— 协议名称name- 一个 gettable 属性message()- 没有任何实现的方法定义
使类符合 Swift 协议
在 Swift 中,要使用协议,其他类必须符合协议。在我们使类符合协议之后,我们必须提供该方法的实际实现。
下面是如何使类符合协议,
// conform class to Greet protocolclass Employee: Greet {// implementation of propertyvar name = "Perry"// implementation of methodfunc message() {print("Good Morning!")}}
在这里,我们使 Employee 类符合 Greet 协议。因此,我们必须提供 name 属性和 message() 方法的实现。
实例 1:Swift 协议
protocol Greet {// blueprint of propertyvar name: String { get }// blueprint of a methodfunc message()}// conform class to Greet protocolclass Employee: Greet {// implementation of propertyvar name = "Perry"// implementation of methodfunc message() {print("Good Morning", name)}}var employee1 = Employee()employee1.message()
结果为:
Good Morning Perry
在上面的例子中,我们创建了一个名为 Greet 的协议。协议包含 name 属性和 message() 方法的蓝图。
这里,Employee 类符合 Greet,并提供 name 和 message() 的实际实现。
实例 2:计算面积的 Swift 协议
protocol Polygon {func getArea(length: Int, breadth: Int)}// conform the Polygon protocolclass Rectangle: Polygon {// implementation of methodfunc getArea(length: Int, breadth: Int) {print("Area of the rectangle:", length * breadth)}}// create an objectvar r1 = Rectangle()r1.getArea(length:5, breadth: 6)
结果为:
Area of the rectangle: 30
在上面的例子中,我们创建了一个名为 Polygon 的协议。该协议包含带有两个参数的getArea() 方法的蓝图:length 长度和 breadth 宽度。
在这里,Rectangle 类符合 Polygon,并提供了 getArea() 方法的实际实现。
func getArea(length: Int, breadth: Int) {print("Area of the rectangle:", length * breadth)}
符合多个协议
在 Swift 中,一个类也可以符合多个协议。例如,
protocol Sum {...}protocol Multiplication {...}class Calculate: Sum, Multiplication {...}
这里,名为 Calculate 的类符合 Sum 和 Multiplication 协议。
实例 3:符合多个协议
// create Sum protocolprotocol Sum {func addition()}// create Multiplication protocolprotocol Multiplication {func product()}// conform class to two protocolsclass Calculate: Sum, Multiplication {var num1 = 0var num2 = 0func addition () {let result1 = num1 + num2print("Sum:", result1)}func product () {let result2 = num1 * num2print("Product:", result2)}}// create an objectvar calc1 = Calculate()// assign values to propertiescalc1.num1 = 5calc1.num2 = 10// access methodscalc1.addition()calc1.product()
结果如下:
Sum: 15Product: 50
在上面的实例中,我们创建了两个协议:Sum 和 Multiplication。此外,我们还创建了一个名为 Calculate 的类,它符合这两个协议。
我们在 Sum 和 Multiplication 协议中分别创建了名为 addition() 和 product() 的方法蓝图。
protocol Sum {func addition()}protocol Multiplication {func product()}
由于 Calculate 符合 Sum 和 Multipalization,因此我们在类中提供了 addition() 和 product() 的实际实现。
最后,我们使用类的 calc1 对象访问了这些方法。
// access methodscalc1.addition()calc1.product()
Swift 协议继承
与类类似,协议可以继承其他协议。例如,
protocol Car {...}protocol Brand: Car {...}
这里,Brand 协议继承了 Car 协议。现在,如果任何类实现了 Brand,那么它应该为 Car 和 Brand 的所有属性提供实现。
实例 4: Swift 协议继承
protocol Car {var colorOptions: Int { get }}// inherit Car protocolprotocol Brand: Car {var name: String { get }}class Mercedes: Brand {// must implement properties of both protocolsvar name: String = ""var colorOptions: Int = 0}var car1 = Mercedes()car1.name = "Mercedes AMG"car1.colorOptions = 4print("Name:", car1.name)print("Color Options:", car1.colorOptions)
结果如下:
Name: Mercedes AMGColor Options: 4
在上面的实例中,Brand 协议继承了 Car 协议。
这里,Mercedes 仅符合 Brand。但由于 Brand 继承了 Car,我们需要实现 Car 和 Brand 的所有属性。
protocol A {...}protocol B {...}protocol C: A, B {...}
协议扩展
在 Swift 中,我们可以使用 extension 关键字扩展协议。例如,
// protocol definitionprotocol Brake {func applyBrake()}// define class that conforms Brakeclass Car: Brake {var speed: Int = 0func applyBrake() {print("Brake Applied")}}// extend protocolextension Brake {func stop() {print("Engine Stopped")}}let car1 = Car()car1.speed = 61print("Speed:", car1.speed)car1.applyBrake()// access extended protocolcar1.stop()
结果如下:
Speed: 61Brake AppliedEngine Stopped
在上面的实例中,我们创建了定义函数 applyBrake() 的协议 Brake。
我们扩展了 Brake 协议,并在其中定义了 stop() 函数。
// extend protocolextension Brake {func stop() {print("Engine Stopped")}}
我们可以使用 car1 对象访问扩展协议。
// access extended protocolcar1.stop()