Swift Protocols 怎么用?协议在 Swift 中如何定义和实现?

文章导读
Previous Quiz Next 协议为方法、属性和其他要求功能提供了一个蓝图。它仅被描述为方法或属性的骨架,而不是实现。方法和属性的实现可以通过定义 class、function 和 enumeration 来进一步完成。协议的从属(conformance)被定义为满
📋 目录
  1. 在 Swift 中定义协议
  2. 属性、方法和初始化要求
  3. 协议作为类型
  4. 使用扩展添加协议遵循
  5. 协议继承
  6. 仅限 Class 的 Protocols
  7. Protocol Composition
  8. 检查 Protocol Conformance
A A

Swift - 协议



Previous
Quiz
Next

协议为方法、属性和其他要求功能提供了一个蓝图。它仅被描述为方法或属性的骨架,而不是实现。方法和属性的实现可以通过定义 class、function 和 enumeration 来进一步完成。协议的从属(conformance)被定义为满足协议要求的方法或属性。

在 Swift 中定义协议

在 Swift 中,协议的定义与 class、structure 或 enumeration 非常相似。协议使用 protocol 关键字定义。

语法

以下是协议的语法 —

protocol SomeProtocol {
   // 协议定义 
}

协议在 class、structure 或 enumeration 类型名称之后声明。也可以声明单个或多个协议。如果定义多个协议,则它们必须用逗号分隔。

struct SomeStructure: Protocol1, Protocol2 {
   // structure 定义 
}

当需要为 superclass 定义协议时,协议名称应紧跟在 superclass 名称后,用逗号分隔。

class SomeClass: SomeSuperclass, Protocol1, Protocol2 {
   // class 定义 
}

属性、方法和初始化要求

协议要求任何符合的类型提供属性、方法和初始化。

属性要求 − 协议用于指定特定的类类型属性或实例属性。它仅指定类型或实例属性,而不指定它是存储属性还是计算属性。同时,还需指定属性是“可获取”的还是“可设置”的。

属性要求通过 'var' 关键字声明为属性变量。在类型声明后使用 {get set} 来声明可获取和可设置的属性。在类型声明后使用 {get} 来表示可获取属性。

语法

以下语法用于在协议中定义属性 −

protocol SomeProtocol {
   var propertyName : Int {get set}
}

方法要求 − 协议用于指定特定类型方法或实例方法。它仅包含定义部分,没有大括号和方法体。它允许方法具有可变参数。

语法

以下语法用于在协议中定义方法 −

protocol SomeProtocol {
   func methodName(parameters)
}

可变方法要求 − 如果要在协议中指定可变方法,则在方法定义前使用 mutating 关键字。这允许结构体和枚举采用包含可变方法的协议。

语法

以下语法用于在协议中定义可变方法 −

protocol SomeProtocol {
   mutating func methodName(parameters)
}

初始化器要求:协议还用于指定将由符合类型实现的初始化器。它仅包含定义部分,就像普通初始化器一样,但没有大括号和方法体。我们可以指定指定初始化器或便利初始化器。

此外,符合协议的类或结构体必须在初始化器的实现前使用 required 修饰符。通过 'required' 修饰符确保协议符合性在所有子类中得到保证,无论是以显式还是继承的方式实现。当子类覆盖其超类的初始化要求时,使用 'override' 修饰符关键字指定。

语法

以下语法用于在协议中定义初始化器 −

protocol SomeProtocol {
  init(parameters)
}

示例

Swift 程序,用于创建一个由类符合的协议。

// Protocol
protocol classa {

   // Properties
   var marks: Int { get set }
   var result: Bool { get }
   
   // Method
   func attendance() -> String
   func markssecured() -> String
}

// Protocol
protocol classb: classa {
   
   // Properties
   var present: Bool { get set }
   var subject: String { get set }
   var stname: String { get set }
}

// Class that conform Protocol
class classc: classb {
   var marks = 96
   let result = true
   var present = false
   var subject = "Swift 4 Protocols"
   var stname = "Protocols"
   
   func attendance() -> String {
      return "The \(stname) has secured 99% attendance"
   }
   
   func markssecured() -> String {
      return "\(stname) has scored \(marks)"
   }
}

// Instance of class
let studdet = classc()
studdet.stname = "Swift 4"
studdet.marks = 98

// Accessing methods and properties
print(studdet.markssecured())

print(studdet.marks)
print(studdet.result)
print(studdet.present)
print(studdet.subject)
print(studdet.stname)

输出

它将产生以下输出 −

Swift 4 has scored 98
98
true
false
Swift 4 Protocols
Swift 4

示例

Swift 程序,用于创建一个带有可变方法要求的协议。

// Protocol
protocol daysofaweek {
   // Mutating method
   mutating func display()
}

// Enumeration that conforms to the Protocol
enum days: daysofaweek {
   case sun, mon, tue, wed, thurs, fri, sat
    
   mutating func display() {
      switch self {
         case .sun:
            print("Sunday")
         case .mon:
            print("Monday")
         case .tue:
            print("Tuesday")
         case .wed:
            print("Wednesday")
         case .thurs:
            print("Thursday")
         case .fri:
            print("Friday")
         case .sat:
            print("Saturday")
      }
   }
}

// Instance of enumeration
var res = days.wed
res.display()

输出

它将产生以下输出 −

Wednesday

示例

Swift 程序,用于创建一个带有初始化器的协议,该初始化器由类符合。

// Protocol
protocol tcpprotocol {

   // Initializer
   init(no1: Int)
}

class mainClass {
   var no1: Int // local storage
   init(no1: Int) {
      self.no1 = no1 // initialization
   }
}

// Class that conform protocol 
class subClass: mainClass, tcpprotocol {
   var no2: Int
   init(no1: Int, no2 : Int) {
      self.no2 = no2
      super.init(no1:no1)
   }
   
   // Requires only one parameter for convenient method
   required override convenience init(no1: Int)  {
      self.init(no1:no1, no2:0)
   }
}

// Class instances
let obj1 = mainClass(no1: 20)
let obj2 = subClass(no1: 30, no2: 50)

print("res is: \(obj1.no1)")
print("res is: \(obj2.no1)")
print("res is: \(obj2.no2)")

输出

它将产生以下输出 −

res is: 20
res is: 30
res is: 50

协议作为类型

协议不是用来实现功能,而是用作函数、class、方法等的类型。协议可以作为类型在以下地方使用:

  • 函数、方法或初始化器作为参数或返回类型

  • 常量、变量或属性

  • 数组、字典或其他容器作为元素

示例

protocol Generator {
   associatedtype Element
   mutating func next() -> Element?
}

extension Array: Generator {
   mutating func next() -> Element? {
      guard !isEmpty else { return nil }
      return removeFirst()
   }
}

var items = [10, 20, 30]
while let x = items.next() {
   print(x)
}

for lists in [1, 2, 3].compactMap({ i in i * 5 }) {
   print(lists)
}

print([100, 200, 300])
print([1, 2, 3].map({ i in i * 10 }))

输出

它将产生以下输出 −

10
20
30
5
10
15
[100, 200, 300]
[10, 20, 30]

使用扩展添加协议遵循

现有的类型可以通过使用扩展来采用并遵循新的协议。借助扩展,可以为现有类型添加新的属性、方法和下标。

示例

protocol AgeClassificationProtocol {
   var age: Int { get }
   func ageType() -> String
}

class Person: AgeClassificationProtocol {
   let firstname: String
   let lastname: String
   var age: Int

   init(firstname: String, lastname: String, age: Int) {
      self.firstname = firstname
      self.lastname = lastname
      self.age = age
   }

   func fullname() -> String {
      return firstname + " " + lastname
   }

   func ageType() -> String {
      switch age {
         case 0...2:
            return "Baby"
         case 3...12:
            return "Child"
         case 13...19:
            return "Teenager"
         case 65...:
            return "Elderly"
         default:
            return "Normal"
        }
    }
}

let obj = Person(firstname: "Mona", lastname: "Singh", age: 10)
print("Full Name: \(obj.fullname())")
print("Age Type: \(obj.ageType())")

输出

它将产生以下输出 −

Full Name: Mona Singh
Age Type: Child

协议继承

Swift 允许协议从其定义的属性继承属性。这类似于 class 继承,但可以选择列出多个用逗号分隔的继承协议。借助协议,我们可以实现类无法实现的多重继承。

语法

以下是协议继承的语法 −

protocol SomeProtocol: protocol1, protocol2 {
  // statement
}

示例

protocol ClassA {
   var no1: Int { get set }
   func calc(sum: Int)
}

protocol Result {
   func print(target: ClassA)
}

class Student2: Result {
   func print(target: ClassA) {
      target.calc(sum: 1)
   }
}

class ClassB: Result {
   func print(target: ClassA) {
      target.calc(sum: 5)
   }
}

class Student: ClassA {
   var no1: Int = 10
    
   func calc(sum: Int) {
      no1 -= sum
      print("Student attempted \(sum) times to pass")
        
      if no1 <= 0 {
         print("Student is absent for the exam")
      }
   }
}

class Player {
   var stmark: Result!
    
   init(stmark: Result) {
      self.stmark = stmark
   }
    
   func print(target: ClassA) {
      stmark.print(target: target)
   }
}

var marks = Player(stmark: Student2())
var marksec = Student()

marks.print(target: marksec)
marks.print(target: marksec)
marks.print(target: marksec)

marks.stmark = ClassB()
marks.print(target: marksec)
marks.print(target: marksec)
marks.print(target: marksec)

输出

它将产生以下输出 −

Student attempted 1 times to pass
Student attempted 1 times to pass
Student attempted 1 times to pass
Student attempted 5 times to pass
Student attempted 5 times to pass
Student is absent for exam
Student attempted 5 times to pass
Student is absent for exam

仅限 Class 的 Protocols

当定义 protocols,并且用户希望为 class 定义 protocol 时,应首先定义 class,然后添加 protocol 的继承列表。

示例

protocol tcpprotocol {
   init(no1: Int)
}

class mainClass {
   var no1: Int // 本地存储
   init(no1: Int) {
      self.no1 = no1 // 初始化
   }
}

class subClass: mainClass, tcpprotocol {
   var no2: Int
   init(no1: Int, no2 : Int) {
      self.no2 = no2
      super.init(no1:no1)
   }
   
   // 仅需一个参数以提供便捷方法
   required override convenience init(no1: Int)  {
      self.init(no1:no1, no2:0)
   }
}

let res = mainClass(no1: 20)
let obj = subClass(no1: 30, no2: 50)

print("res is: \(res.no1)")
print("res is: \(obj.no1)")
print("res is: \(obj.no2)")

输出

它将产生以下输出 −

res is: 20
res is: 30
res is: 50

Protocol Composition

Swift 通过 protocol composition 允许同时调用多个 protocols。我们可以使用 protocol composition 将多个 protocols 组合到一个单一的要求中。它不会定义任何新的 protocol 类型,只使用现有的类型。

在 protocol composition 中,我们可以指定任意数量的 protocol,每个 protocol 由 & 分隔。它还可以包含一个 class 类型,用于指定 superclass。

语法

protocol<SomeProtocol & AnotherProtocol>

示例

protocol StName {
   var name: String { get }
}

protocol Stage {
   var age: Int { get }
}

struct Person: StName, Stage {
   var name: String
   var age: Int
}

// Protocol Composition
func printCelebrator(celebrator: StName & Stage) {
   print("\(celebrator.name) is \(celebrator.age) years old")
}

let studName = Person(name: "Priya", age: 21)
printCelebrator(celebrator: studName)

let stud = Person(name: "Rehan", age: 29)
printCelebrator(celebrator: stud)

let student = Person(name: "Roshan", age: 19)
printCelebrator(celebrator: student)

输出

它将产生以下输出 −

Priya is 21 years old
Rehan is 29 years old
Roshan is 19 years old

检查 Protocol Conformance

Protocol conformance 使用 'is' 和 'as' 操作符进行测试,类似于 type casting。

  • is 操作符如果实例符合 protocol 标准则返回 true,否则返回 false。

  • as? 版本的 downcast 操作符返回 protocol 类型的一个 optional 值,如果实例不符合该 protocol,则该值为 nil。

  • as 版本的 downcast 操作符强制 downcast 到 protocol 类型,如果 downcast 失败则触发运行时错误。

示例

import Foundation
@objc protocol rectangle {
   var area: Double { get }
}

@objc class Circle: rectangle {
   let pi = 3.1415927
   var radius: Double
   var area: Double { return pi * radius * radius }
   init(radius: Double) { self.radius = radius }
}

@objc class result: rectangle {
   var area: Double
   init(area: Double) { self.area = area }
}

class sides {
   var rectsides: Int
   init(rectsides: Int) { self.rectsides = rectsides }
}
let objects: [AnyObject] = [Circle(radius: 2.0),result(area: 198),sides(rectsides: 4)]

for object in objects {
   if let objectWithArea = object as? rectangle {
      print("Area is \(objectWithArea.area)")
   } else {
      print("Rectangle area is not defined")
   }
}

输出

它将产生以下输出 −

Area is 12.5663708
Area is 198.0
Rectangle area is not defined