什么是Protocol?
protocol是swift中的一种自定义约束,一般用于定义某些类的一种共同特性
定义一个protocol
protocol Student {
func getName()
func getGrade()
}
某个class、struct、enum遵守这个约定,需要实现约定的方法(注意:如果里面的方法有参数,不能有默认值)
struct Person:Student {
func getName() {
print("my name")
}
func getGrade() {
print("my grade")
}
}
protocol中也可以定义属性,定义的属性必须制定该属性支持的操作(get、set)
protocol PersonProtocol{
var height:Int{get set}
func getName()
func getSex()
func getgrade(name:String)
func getAge(age:Int)
// func getAge(age:Int = 0) ❌ Default argument not permitted in a protocol method
}
height在protocol中是一个computed property,但在遵守该约定的类型中可以简单的定义成一个stored property
当protocol中定义了一个只读属性,其实我们也可以在遵守该约定的类型中完成该属性的可读可写
protocol PersonProtocol{
var height:Int{get set}
var weight:Int{get}
func getName()
func getSex()
func getgrade(name:String)
func getAge(age:Int)
}
struct Person:PersonProtocol {
var height: Int = 178
var weight: Int = 120
func getName() {
print("my name")
}
func getSex() {
print("my sex")
}
func getgrade(name: String) {
print("my grade")
}
func getAge(age: Int) {
print("my age")
}
}
var person1 = Person()
person1.height // 178
person1.height = 189
person1.height // 189
person1.weight // 120
person1.weight = 160
// 当我们把person从Person转换成PersonProtocol时 他就是只读的了
(person1 as PersonProtocol).weight = 160 //cannot assign to property: 'weight' is a get-only property