Swift 中 Protocol 的定义及使用
1. Protocol的定义
让我们来创建一个简单的例子来说明 Swift 中如何定义和使用协议。
首先,我们定义一个协议 Animal,它具有两个方法 makeSound 和 move:
protocol Animal {
func makeSound()
func move()
}
然后,我们创建两个类 Dog 和 Cat,它们都遵循了 Animal 协议,并实现了协议中的方法:
class Dog: Animal {
func makeSound() {
print("Woof!")
}
func move() {
print("Running")
}
}
class Cat: Animal {
func makeSound() {
print("Meow!")
}
func move() {
print("Walking")
}
}
现在我们可以创建一些实例,并调用它们的方法:
let dog = Dog()
let cat = Cat()
dog.makeSound() // 输出: Woof!
dog.move() // 输出: Running
cat.makeSound() // 输出: Meow!
cat.move() // 输出: Walking
在这个例子中,我们定义了一个 Animal 协议,该协议包含了两个方法 makeSound 和 move,然后我们创建了 Dog 和 Cat 两个类,它们都遵循了 Animal 协议,并实现了协议中的方法。最后,我们创建了 Dog 和 Cat 的实例,并调用了它们的方法来展示它们的行为。这种方式使得我们可以在不同的类之间实现相同的行为,并且可以轻松地切换和扩展这些行为。
2. Protocol 协议实现条件的限定
其中,我们对 ListToDetailProtocol 进行扩展,限定关联类型 TemplateModel 为 OldTemplate,同时限定遵循协议的类型为 UIViewController:
import Foundation
// 定义一个协议 ListToDetailProtocol,用于在列表和详情页之间进行通信
protocol ListToDetailProtocol {
// 关联类型,用于指定具体的模型类型
associatedtype TemplateModel
/// 列表选某个进详情页
func pushDetail(with index: Int, temps: [TemplateModel], animated: Bool)
}
// 对 ListToDetailProtocol 进行扩展,限定关联类型 TemplateModel 为 OldTemplate,同时限定遵循协议的类型为 UIViewController
extension ListToDetailProtocol where Self: UIViewController, TemplateModel == OldTemplate {
/// 列表选某个进详情页
func pushDetail(with index: Int, temps: [TemplateModel], animated: Bool = true) {
// 创建一个 TemplateDetailController 实例
let vc = TemplateDetailController()
// 设置 functionFrom 属性为 .animate
vc.functionFrom = .animate
// 设置 templateIndex 属性为传入的 index
vc.templateIndex = index
// 设置 originalTemplateArray 属性为传入的 temps
vc.originalTemplateArray = temps
// 将详情页控制器压入导航栈中,可选择是否动画显示
navigationController?.pushViewController(vc, animated: animated)
}
}
3. 将1中的示例改成2中的逻辑
首先,我们定义一个协议 ListToDetailProtocol,它有一个关联类型 TemplateModel,并有一个方法 pushDetail,用于在列表选中某个项目后跳转到详情页。
protocol ListToDetailProtocol {
associatedtype TemplateModel
func pushDetail(with index: Int, temps: [TemplateModel], animated: Bool)
}
然后,我们创建一个类 AnimalListViewController,它遵循了 ListToDetailProtocol 协议,并在该类的扩展中实现了 pushDetail 方法,该方法用于将动物的详情页推入导航栈中。
import UIKit
class AnimalListViewController: UIViewController, ListToDetailProtocol {
typealias TemplateModel = Animal
func pushDetail(with index: Int, temps: [Animal], animated: Bool = true) {
guard index < temps.count else {
print("Invalid index")
return
}
let selectedAnimal = temps[index]
let detailVC = AnimalDetailViewController(animal: selectedAnimal)
navigationController?.pushViewController(detailVC, animated: animated)
}
}
// Animal 是一个简单的模型,代表一个动物
struct Animal {
let name: String
let species: String
}
接下来,我们创建一个 AnimalDetailViewController 类,用于显示动物的详情页:
class AnimalDetailViewController: UIViewController {
let animal: Animal
init(animal: Animal) {
self.animal = animal
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// 在视图中显示动物的名称和种类
let nameLabel = UILabel(frame: CGRect(x: 50, y: 100, width: 200, height: 30))
nameLabel.text = "Name: \(animal.name)"
view.addSubview(nameLabel)
let speciesLabel = UILabel(frame: CGRect(x: 50, y: 150, width: 200, height: 30))
speciesLabel.text = "Species: \(animal.species)"
view.addSubview(speciesLabel)
}
}
最后,我们可以创建一些动物的实例,并使用 AnimalListViewController 来显示列表并跳转到详情页:
let dog = Animal(name: "Buddy", species: "Dog")
let cat = Animal(name: "Whiskers", species: "Cat")
let animalListVC = AnimalListViewController()
animalListVC.pushDetail(with: 0, temps: [dog, cat], animated: true)
这个例子中,我们通过 ListToDetailProtocol 协议和其扩展实现了一个列表到详情页的通用逻辑。然后,我们创建了一个 AnimalListViewController 类,并使用该类来展示动物列表并跳转到动物的详情页。