在我的示例中,我有两个类,每个类都有一个相同的函数message
,我的目标是将两个函数合并为一个,以减少维护工作。我已经编写了很多文档,发现protocol
可能是实现这一点的方法。然而,基于示例1:Swift Protocol。我仍然不明白如何在访问变量name
的情况下,在Greet协议下调用消息函数中的print
函数
protocol Greet {
// blueprint of property
var name: String { get }
// blueprint of a method
func message() // ???? how to write the print function and access to name variable ??
}
// conform class to Greet protocol
class Employee: Greet {
// implementation of property
var name = "Perry"
// implementation of method
func message() {
print("Good Morning", name)
}
}
class Student: Greet {
var name = "student abc"
func message() {
print("Good Morning", name)
}
}
var employee1 = Employee()
employee1.message()
var student = Student()
student.message()
这就是面向协议编程的美妙之处。您的协议扩展可以定义一个默认实现,默认情况下,所有符合协议的类型都将继承该实现。
因此,如果您的协议是:
protocol Greet {
var name: String { get }
func message()
}
您可以定义符合类型将继承的默认实现。
extension Greet {
func message() {
print("Good Morning", name)
}
}
这样,您的一致性类型就不需要实现任何在协议扩展中定义了默认实现的东西。
class Employee: Greet {
var name = "Perry"
}
用法如下:
let employee = Employee()
employee.message()
然后打印:
早上好Perry
概述
您需要扩展协议以提供默认实现(您不能直接这样做,因为协议只是一组需求,所以扩展可以提供实现(
代码
extension Greet {
func message() {
print("Good Morning", name)
}
}
参考
https://docs.swift.org/swift-book/LanguageGuide/Protocols.html#ID277