这是我参与更文挑战的第2天,活动详情查看: 更文挑战
面向协议编程pop – (protocol-oriented programming)
协议描述一个东西必须含有的属性和方法; 你可以告诉swift类来遵守这个协议
比如 : 我们写一个函数,接受一个 id 属性。但是你不需要关心这个数据类型;我们创建一个Identifiable 协议,其他遵守这个协议的的对象都需要有一个 id String, 同时需要具备 “get” 和 “set”
protocol Identifiable {
var id: String { get set }
}
复制代码
struct User: Identifiable {
var id: String
}
复制代码
func displayID(thing: Identifiable) {
print("My ID is \(thing.id)")
}
复制代码
协议继承
协议可以继承另外一个定义好的协议,跟class 不一样的是,同一时间你可以继承多个 protocol 协议
protocol Payable {
func calculateWages() -> Int
}
protocol NeedsTraining {
func study()
}
protocol HasVacation {
func takeVacation(days: Int)
}
复制代码
创建一个Employee ,遵守上面定义好的,多个协议使用,分割;
protocol Employee: Payable, NeedsTraining, HasVacation { }
复制代码
Extensions 扩展
- Swift中的扩展,类似OC中的分类Category
- 扩展可以为枚举、结构体、类、协议添加新功能
extensions 容许我们给存在types 添加扩展方法,增加一个原本没有方法;
同名方法会报错:OC中是允许覆盖的,但Swift是安全的,是不允许覆盖的
extension Int {
func squared() -> Int {
return self * self
}
}
let number = 8
number.squared()
复制代码
swift 不能在扩展中添加存储属性;可以使用计算属性来替代
因为存储属性会改变内存结构,但扩展是不允许改变原有结构的
extension Int {
var isEven: Bool {
return self % 2 == 0
}
}
复制代码
面向协议编程(POP)
Protocol 扩展能提供一个默认的实现,对于我们定义的协议方法
比如我们有一个协议叫做 Identifiable,他要求我们有一个id 属性 和 identify()
方法
protocol Identifiable {
var id: String { get set }
func identify()
}
复制代码
提供一个默认的实现
extension Identifiable {
func identify() {
print("My ID is \(id).")
}
}
复制代码
User 对象只要遵守,Identifiable 协议,就能自动调用identify() 函数
struct User: Identifiable {
var id: String
}
let twostraws = User(id: "twostraws")
twostraws.identify()
复制代码
Protocol and Delegate (协议与代理)
委托(Delegate)是一种设计模式,表示将一个对象的部分功能转交给另一个对象。委托模式可以用来响应特定的动作,或者接收外部数据源提供的数据,而无需关心外部数据源的类型。部分情况下,Delegate 比起自上而下的继承具有更松的耦合程度,有效的减少代码的复杂程度。
那么 Deleagte 和 Protocol 之间是什么关系呢?在 Swift 中,Delegate 就是基于 Protocol 实现的,定义 Protocol 来封装那些需要被委托的功能,这样就能确保遵循协议的类型能提供这些功能。
Protocol 是 Swift 的语言特性之一,而 Delegate 是利用了 Protocol 来达到解耦的目的。
protocol CustomButtonDelegate: AnyObject{
func CustomButtonDidClick()
}
class ACustomButton: UIView {
weak var delegate: CustomButtonDelegate?
func didClick() {
delegate?.CustomButtonDidClick()
}
}
// 遵循委托的类
class ViewController: UIViewController, CustomButtonDelegate {
let buttonView:ACustomButton = ACustomButton()
override
func viewDidLoad() {
super.viewDidLoad()
buttonView.delegate = self
}
func CustomButtonDidClick() {
print("Delegation works!")
}
}
复制代码
总结
- 协议定义了必须遵守契约
- 可以遵守很多个协议,获得超能力方法;calss 不能多继承
- 协议扩展 Extensions 可以提供默认的实现
- 面向协议编程pop
- 协议与代理的关系