Swift - 协议



协议提供方法、属性和其他需求功能的蓝图。它仅仅描述为方法或属性的骨架,而不是实现。方法和属性的实现可以通过定义类、函数和枚举来进一步完成。协议的遵循被定义为方法或属性满足协议的要求。

在 Swift 中定义协议

在 Swift 中,协议的定义与类、结构体或枚举非常相似。协议使用  **protocol**  关键字定义。

语法

以下是协议的语法:

protocol SomeProtocol {
   // protocol definition 
}

协议声明在类、结构体或枚举类型名称之后。单协议和多协议声明都是可能的。如果定义了多个协议,则必须用逗号分隔。

struct SomeStructure: Protocol1, Protocol2 {
   // structure definition 
}

当必须为超类定义协议时,协议名称应在超类名称后用逗号分隔。

class SomeClass: SomeSuperclass, Protocol1, Protocol2 {
   // class definition 
}

属性、方法和初始化器要求

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

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

属性要求由 '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

协议作为类型

协议不用于实现功能,而是用作函数、类、方法等的类型。协议可以在以下方面用作类型:

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

  • 常量、变量或属性

  • 数组、字典或其他容器中的项目

示例

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 允许协议从其定义的属性继承属性。这类似于类的继承,但可以选择列出用逗号分隔的多个继承协议。借助协议,我们可以实现使用类无法实现的多重继承。

语法

以下是协议继承的语法:

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

仅限类协议

当定义协议时,如果用户想要使用类定义协议,则应首先定义类,然后定义协议的继承列表。

示例

protocol tcpprotocol {
   init(no1: Int)
}

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

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)
   }
}

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

协议组合

Swift 允许使用协议组合同时调用多个协议。我们可以使用协议组合将多个协议组合到单个需求中。它不定义任何新的协议类型,而只使用现有的协议。

在协议组合中,我们可以根据需要指定任意数量的协议,其中每个协议都用按位与符号 (&) 分隔。它还可以包含一个类类型,我们可以用它来指定超类。

语法

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

检查协议一致性

协议一致性由 'is' 和 'as' 运算符测试,类似于类型转换。

  • 'is' 运算符如果实例符合协议标准则返回 true,如果不符合则返回 false。

  • 'as?' 版本的向下转换运算符返回协议类型的可选值,如果实例不符合该协议,则此值为 nil。

  • 'as' 版本的向下转换运算符强制向下转换为协议类型,如果向下转换不成功,则会触发运行时错误。

示例

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
广告
© . All rights reserved.