Swift协议
协议规定了用来实现某一特定功能所必需的方法和属性。
任意能够满足协议要求的类型被称为遵循(conform)这个协议。
类、结构体或枚举类型都可以遵循协议,并提供具体实现来完成协议定义的方法和功能。
语法
协议的语法格式如下:
protocol SomeProtocol { // 协议内容 }
要使类遵循某个协议,需要在类型名称后加上协议名称,中间以冒号:分隔,作为类型定义的一部分。遵循多个协议时,各协议之间用逗号,分隔。
struct SomeStructure: FirstPortocol, AnotherProtocol { // 结构体内容 }
如果类在遵循协议的同时拥有父类,应该将父类名放在协议名之前,以逗号分隔。
class SomeClass: SomeSuperClass, FirstProtocol, AnotherProtocol { // 类的内容 }
对属性的规定
协议用于指定特定的实例属性或类属性,而不用指定是存储型属性或计算型属性。此外还必须指明是只读的还是可读可写的。
协议中的通常用var来声明变量属性,在类型声明后加上{set get}来表示属性是可读可写的,只读属性则用{get}来表示。
protocol someClass { // 可读可写属性 var marks: Int {set get} // 只读属性 var result: Bool {get} func attendance() -> String func markssecured() -> String } protocol anotherClass: someClass { var present: Bool {get set} var subject: String {get set} var stname: String {get set} } class classStudent: anotherClass { var marks: Int = 96 var result: Bool = true var present: Bool = false var subject: String = "Swift 协议" var name: String = "Protocols" func attendance() -> String { return "The \(name) has secured 99% attendance" } func markssecured() -> String { return "\(name) has scored \(marks)" } } let student = classStudent() student.name = "Swift" student.marks = 98 student.markssecured() print(student.marks, student.result, student.present, student.subject, student.name)
对Mutating方法的规定
有时需要在方法中改变它的实例。
例如:值类型(结构体,枚举)的实例方法中,将mutating关键字作为函数的前缀,写在func之前,表示可以在该方法中修改它所属的实例及其实例属性的值。
protocol week { mutating func show() } enum days: week { case sun, mon, tue, wed, thurs, fri, sat mutating func show() { switch self { case .sun: self = .sun print("周日") case .mon: self = .mon print("周一") case .tue: self = .tue print("周二") case .wed: self = .wed print("周三") case .thurs: self = .thurs print("周四") case .fri: self = .fri print("周五") case .sat: self = .sat print("周六") default: print("查无此日") } } } var res = days.wed res.show()