Swift 协议


协议规定了用来实现某一特定功能所必需的方法和属性。

任意能够满足协议要求的类型被称为遵循(conform)这个协议。

类,结构体或枚举类型都可以遵循协议,并提供具体实现来完成协议定义的方法和功能。

语法

协议的语法格式如下:

  1. protocol SomeProtocol {
  2. // 协议内容
  3. }

要使类遵循某个协议,需要在类型名称后加上协议名称,中间以冒号:分隔,作为类型定义的一部分。遵循多个协议时,各协议之间用逗号,分隔。

  1. struct SomeStructure: FirstProtocol, AnotherProtocol {
  2. // 结构体内容
  3. }

如果类在遵循协议的同时拥有父类,应该将父类名放在协议名之前,以逗号分隔。

  1. class SomeClass: SomeSuperClass, FirstProtocol, AnotherProtocol {
  2. // 类的内容
  3. }

对属性的规定

协议用于指定特定的实例属性或类属性,而不用指定是存储型属性或计算型属性。此外还必须指明是只读的还是可读可写的。

协议中的通常用var来声明变量属性,在类型声明后加上{ set get }来表示属性是可读可写的,只读属性则用{ get }来表示。

  1. protocol classa {
  2. var marks: Int { get set }
  3. var result: Bool { get }
  4. func attendance() -> String
  5. func markssecured() -> String
  6. }
  7.  
  8. protocol classb: classa {
  9. var present: Bool { get set }
  10. var subject: String { get set }
  11. var stname: String { get set }
  12. }
  13.  
  14. class classc: classb {
  15. var marks = 96
  16. let result = true
  17. var present = false
  18. var subject = "Swift 协议"
  19. var stname = "Protocols"
  20. func attendance() -> String {
  21. return "The \(stname) has secured 99% attendance"
  22. }
  23. func markssecured() -> String {
  24. return "\(stname) has scored \(marks)"
  25. }
  26. }
  27.  
  28. let studdet = classc()
  29. studdet.stname = "Swift"
  30. studdet.marks = 98
  31. studdet.markssecured()
  32.  
  33. print(studdet.marks)
  34. print(studdet.result)
  35. print(studdet.present)
  36. print(studdet.subject)
  37. print(studdet.stname)

以上程序执行输出结果为:

  1. 98
  2. true
  3. false
  4. Swift 协议
  5. Swift

对 Mutating 方法的规定

有时需要在方法中改变它的实例。

例如,值类型(结构体,枚举)的实例方法中,将mutating关键字作为函数的前缀,写在func之前,表示可以在该方法中修改它所属的实例及其实例属性的值。

  1. protocol daysofaweek {
  2. mutating func show()
  3. }
  4.  
  5. enum days: daysofaweek {
  6. case sun, mon, tue, wed, thurs, fri, sat
  7. mutating func show() {
  8. switch self {
  9. case .sun:
  10. self = .sun
  11. print("Sunday")
  12. case .mon:
  13. self = .mon
  14. print("Monday")
  15. case .tue:
  16. self = .tue
  17. print("Tuesday")
  18. case .wed:
  19. self = .wed
  20. print("Wednesday")
  21. case .thurs:
  22. self = .thurs
  23. print("Wednesday")
  24. case .fri:
  25. self = .fri
  26. print("Wednesday")
  27. case .sat:
  28. self = .sat
  29. print("Saturday")
  30. default:
  31. print("NO Such Day")
  32. }
  33. }
  34. }
  35.  
  36. var res = days.wed
  37. res.show()

以上程序执行输出结果为:

  1. Wednesday

对构造器的规定

协议可以要求它的遵循者实现指定的构造器。

你可以像书写普通的构造器那样,在协议的定义里写下构造器的声明,但不需要写花括号和构造器的实体,语法如下:

  1. protocol SomeProtocol {
  2. init(someParameter: Int)
  3. }

实例

  1. protocol tcpprotocol {
  2. init(aprot: Int)
  3. }

协议构造器规定在类中的实现

你可以在遵循该协议的类中实现构造器,并指定其为类的指定构造器或者便利构造器。在这两种情况下,你都必须给构造器实现标上"required"修饰符:

  1. class SomeClass: SomeProtocol {
  2. required init(someParameter: Int) {
  3. // 构造器实现
  4. }
  5. }
  6.  
  7. protocol tcpprotocol {
  8. init(aprot: Int)
  9. }
  10.  
  11. class tcpClass: tcpprotocol {
  12. required init(aprot: Int) {
  13. }
  14. }

使用required修饰符可以保证:所有的遵循该协议的子类,同样能为构造器规定提供一个显式的实现或继承实现。

如果一个子类重写了父类的指定构造器,并且该构造器遵循了某个协议的规定,那么该构造器的实现需要被同时标示required和override修饰符:

  1. protocol tcpprotocol {
  2. init(no1: Int)
  3. }
  4.  
  5. class mainClass {
  6. var no1: Int // 局部变量
  7. init(no1: Int) {
  8. self.no1 = no1 // 初始化
  9. }
  10. }
  11.  
  12. class subClass: mainClass, tcpprotocol {
  13. var no2: Int
  14. init(no1: Int, no2 : Int) {
  15. self.no2 = no2
  16. super.init(no1:no1)
  17. }
  18. // 因为遵循协议,需要加上"required"; 因为继承自父类,需要加上"override"
  19. required override convenience init(no1: Int) {
  20. self.init(no1:no1, no2:0)
  21. }
  22. }
  23. let res = mainClass(no1: 20)
  24. let show = subClass(no1: 30, no2: 50)
  25.  
  26. print("res is: \(res.no1)")
  27. print("res is: \(show.no1)")
  28. print("res is: \(show.no2)")

以上程序执行输出结果为:

  1. res is: 20
  2. res is: 30
  3. res is: 50

协议类型

尽管协议本身并不实现任何功能,但是协议可以被当做类型来使用。

协议可以像其他普通类型一样使用,使用场景:

  • 作为函数、方法或构造器中的参数类型或返回值类型
  • 作为常量、变量或属性的类型
  • 作为数组、字典或其他容器中的元素类型

实例

  1. protocol Generator {
  2. associatedtype members
  3. func next() -> members?
  4. }
  5.  
  6. var items = [10,20,30].makeIterator()
  7. while let x = items.next() {
  8. print(x)
  9. }
  10.  
  11. for lists in [1,2,3].map( {i in i*5}) {
  12. print(lists)
  13. }
  14.  
  15. print([100,200,300])
  16. print([1,2,3].map({i in i*10}))

以上程序执行输出结果为:

  1. 10
  2. 20
  3. 30
  4. 5
  5. 10
  6. 15
  7. [100, 200, 300]
  8. [10, 20, 30]

在扩展中添加协议成员

我们可以可以通过扩展来扩充已存在类型( 类,结构体,枚举等)。

扩展可以为已存在的类型添加属性,方法,下标脚本,协议等成员。

  1. protocol AgeClasificationProtocol {
  2. var age: Int { get }
  3. func agetype() -> String
  4. }
  5.  
  6. class Person {
  7. let firstname: String
  8. let lastname: String
  9. var age: Int
  10. init(firstname: String, lastname: String) {
  11. self.firstname = firstname
  12. self.lastname = lastname
  13. self.age = 10
  14. }
  15. }
  16.  
  17. extension Person : AgeClasificationProtocol {
  18. func fullname() -> String {
  19. var c: String
  20. c = firstname + " " + lastname
  21. return c
  22. }
  23. func agetype() -> String {
  24. switch age {
  25. case 0...2:
  26. return "Baby"
  27. case 2...12:
  28. return "Child"
  29. case 13...19:
  30. return "Teenager"
  31. case let x where x > 65:
  32. return "Elderly"
  33. default:
  34. return "Normal"
  35. }
  36. }
  37. }

协议的继承

协议能够继承一个或多个其他协议,可以在继承的协议基础上增加新的内容要求。

协议的继承语法与类的继承相似,多个被继承的协议间用逗号分隔:
  1. protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
  2. // 协议定义
  3. }

实例

  1. protocol Classa {
  2. var no1: Int { get set }
  3. func calc(sum: Int)
  4. }
  5.  
  6. protocol Result {
  7. func print(target: Classa)
  8. }
  9.  
  10. class Student2: Result {
  11. func print(target: Classa) {
  12. target.calc(1)
  13. }
  14. }
  15.  
  16. class Classb: Result {
  17. func print(target: Classa) {
  18. target.calc(5)
  19. }
  20. }
  21.  
  22. class Student: Classa {
  23. var no1: Int = 10
  24. func calc(sum: Int) {
  25. no1 -= sum
  26. print("学生尝试 \(sum) 次通过")
  27. if no1 <= 0 {
  28. print("学生缺席考试")
  29. }
  30. }
  31. }
  32.  
  33. class Player {
  34. var stmark: Result!
  35. init(stmark: Result) {
  36. self.stmark = stmark
  37. }
  38. func print(target: Classa) {
  39. stmark.print(target)
  40. }
  41. }
  42.  
  43. var marks = Player(stmark: Student2())
  44. var marksec = Student()
  45.  
  46. marks.print(marksec)
  47. marks.print(marksec)
  48. marks.print(marksec)
  49. marks.stmark = Classb()
  50. marks.print(marksec)
  51. marks.print(marksec)
  52. marks.print(marksec)

以上程序执行输出结果为:

  1. 学生尝试 1 次通过
  2. 学生尝试 1 次通过
  3. 学生尝试 1 次通过
  4. 学生尝试 5 次通过
  5. 学生尝试 5 次通过
  6. 学生缺席考试
  7. 学生尝试 5 次通过
  8. 学生缺席考试

类专属协议

你可以在协议的继承列表中,通过添加class关键字,限制协议只能适配到类(class)类型。

该class关键字必须是第一个出现在协议的继承列表中,其后,才是其他继承协议。格式如下:

  1. protocol SomeClassOnlyProtocol: class, SomeInheritedProtocol {
  2. // 协议定义
  3. }

实例

  1. protocol TcpProtocol {
  2. init(no1: Int)
  3. }
  4.  
  5. class MainClass {
  6. var no1: Int // 局部变量
  7. init(no1: Int) {
  8. self.no1 = no1 // 初始化
  9. }
  10. }
  11.  
  12. class SubClass: MainClass, TcpProtocol {
  13. var no2: Int
  14. init(no1: Int, no2 : Int) {
  15. self.no2 = no2
  16. super.init(no1:no1)
  17. }
  18. // 因为遵循协议,需要加上"required"; 因为继承自父类,需要加上"override"
  19. required override convenience init(no1: Int) {
  20. self.init(no1:no1, no2:0)
  21. }
  22. }
  23.  
  24. let res = MainClass(no1: 20)
  25. let show = SubClass(no1: 30, no2: 50)
  26.  
  27. print("res is: \(res.no1)")
  28. print("res is: \(show.no1)")
  29. print("res is: \(show.no2)")

以上程序执行输出结果为:

  1. res is: 20
  2. res is: 30
  3. res is: 50

协议合成

Swift 支持合成多个协议,这在我们需要同时遵循多个协议时非常有用。

语法格式如下:

  1. protocol Stname {
  2. var name: String { get }
  3. }
  4.  
  5. protocol Stage {
  6. var age: Int { get }
  7. }
  8.  
  9. struct Person: Stname, Stage {
  10. var name: String
  11. var age: Int
  12. }
  13.  
  14. func show(celebrator: Stname & Stage) {
  15. print("\(celebrator.name) is \(celebrator.age) years old")
  16. }
  17.  
  18. let studname = Person(name: "Priya", age: 21)
  19. print(studname)
  20.  
  21. let stud = Person(name: "Rehan", age: 29)
  22. print(stud)
  23.  
  24. let student = Person(name: "Roshan", age: 19)
  25. print(student)

以上程序执行输出结果为:

  1. Person(name: "Priya", age: 21)
  2. Person(name: "Rehan", age: 29)
  3. Person(name: "Roshan", age: 19)

检验协议的一致性

你可以使用is和as操作符来检查是否遵循某一协议或强制转化为某一类型。

  • is操作符用来检查实例是否遵循了某个协议
  • as?返回一个可选值,当实例遵循协议时,返回该协议类型;否则返回nil
  • as用以强制向下转型,如果强转失败,会引起运行时错误。

实例

下面的例子定义了一个 HasArea 的协议,要求有一个Double类型可读的 area:

  1. protocol HasArea {
  2. var area: Double { get }
  3. }
  4.  
  5. // 定义了Circle类,都遵循了HasArea协议
  6. class Circle: HasArea {
  7. let pi = 3.1415927
  8. var radius: Double
  9. var area: Double { return pi * radius * radius }
  10. init(radius: Double) { self.radius = radius }
  11. }
  12.  
  13. // 定义了Country类,都遵循了HasArea协议
  14. class Country: HasArea {
  15. var area: Double
  16. init(area: Double) { self.area = area }
  17. }
  18.  
  19. // Animal是一个没有实现HasArea协议的类
  20. class Animal {
  21. var legs: Int
  22. init(legs: Int) { self.legs = legs }
  23. }
  24.  
  25. let objects: [AnyObject] = [
  26. Circle(radius: 2.0),
  27. Country(area: 243_610),
  28. Animal(legs: 4)
  29. ]
  30.  
  31. for object in objects {
  32. // 对迭代出的每一个元素进行检查,看它是否遵循了HasArea协议
  33. if let objectWithArea = object as? HasArea {
  34. print("面积为 \(objectWithArea.area)")
  35. } else {
  36. print("没有面积")
  37. }
  38. }

以上程序执行输出结果为:

  1. 面积为 12.5663708
  2. 面积为 243610.0
  3. 没有面积