Swift - Protocols(协议)

Swift - Protocols(协议) 首页 / Swift入门教程 / Swift - Protocols(协议)

协议Protocols为方法,属性和其他需求函数提供了一个协议。它只是描述为方法或属性框架,而不是实现。方法和属性的实现可以通过子类,函数和枚举来进一步实现。

协议还遵循与类,结构和枚举类似的语法-

无涯教程网

protocol SomeProtocol {
   //协议定义
}

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

struct SomeStructure: Protocol1, Protocol2 {
   //结构定义
}

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

链接:https://www.learnfk.comhttps://www.learnfk.com/swift/swift-protocols.html

来源:LearnFk无涯教程网

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

属性和方法

协议用于指定特定的类类型属性或属性,它仅指定类型或属性,而不指定其是存储属性还是计算属性。此外,它用于指定属性是" gettable"还是" settable"。

属性要求通过'var'关键字声明为属性变量。 {get set}用于在类型声明之后声明gettable和settable属性。在声明类型后,{get}属性会提及Gettable。

protocol classa {
   var marks: Int { get set }
   var result: Bool { get }
   
   func attendance() -> String
   func markssecured() -> String
}

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

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

let studdet=classc()
studdet.stname="Swift 4"
studdet.marks=98
studdet.markssecured()

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

运行上述程序时,我们得到以下输出-

98
true
false
Swift 4 Protocols
Swift 4

Mutating 要求

protocol daysofaweek {
   mutating func print()
}

enum days: daysofaweek {
   case sun, mon, tue, wed, thurs, fri, sat 
   mutating func print() {
      switch self {
         case sun:
            self=sun
            print("Sunday")
         case mon:
            self=mon
            print("Monday")
         case tue:
            self=tue
            print("Tuesday")
         case wed:
            self=wed
            print("Wednesday")
         case mon:
            self=thurs
            print("Thursday")
         case tue:
            self=fri
            print("Friday")
         case sat:
            self=sat
            print("Saturday")
         default:
            print("NO Such Day")
      }
   }
}

var res=days.wed
res.print()

运行上述程序时,我们得到以下输出-

Wednesday

初始化

Swing允许用户初始化协议以遵循与普通初始化程序相似的类型一致性。

protocol SomeProtocol {
   init(someParameter: Int)
}

protocol tcpprotocol {
   init(aprot: Int)
}

初始化协议

指定的或便利的初始化程序允许用户通过保留的" required"关键字初始化协议以符合其标准。

class SomeClass: SomeProtocol {
   required init(someParameter: Int) {
      //初始化器实现语句
   }
}

protocol tcpprotocol {
   init(aprot: Int)
}

class tcpClass: tcpprotocol {
   required init(aprot: Int) {
   }
}

通过" required"修饰符可确保所有子类上的协议一致性,以实现显式或继承的实现。

当子类覆盖其超类初始化要求时,它由'override'修饰符关键字指定。

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 print=subClass(no1: 30, no2: 50)

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

运行上述程序时,我们得到以下输出-

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

协议类型

它们不是在协议中实现函数,而是用作函数,类,方法等的类型。

protocol Generator {
   typealias members
   func next() -> members?
}

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

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

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

运行上述程序时,我们得到以下输出-

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

扩展协议

通过使用扩展,可以采用现有类型并使其符合新协议。可以借助扩展将新的属性,方法和下标添加到现有类型。

protocol AgeClasificationProtocol {
   var age: Int { get }
   func agetype() -> String
}
class Person {
   let firstname: String
   let lastname: String
   var age: Int
   
   init(firstname: String, lastname: String) {
      self.firstname=firstname
      self.lastname=lastname
      self.age=10
   }
}

extension Person : AgeClasificationProtocol {
   func fullname() -> String {
      var c: String
      c=firstname + " " + lastname
      return c
   }
   func agetype() -> String {
      switch age {
         case 0...2:
            return "Baby"
         case 2...12:
            return "Child"
         case 13...19:
            return "Teenager"
         case let x where x > 65:
            return "Elderly"
         default:
            return "Normal"
      }
   }
}

继承协议

Swift 4允许协议从其定义的属性继承属性。它与类继承的类相似,但是可以选择列出多个用逗号分隔的继承协议。

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 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       
   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 print=subClass(no1: 30, no2: 50)

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

运行上述程序时,我们得到以下输出-

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

协议组成

Swift 4允许在协议组合的帮助下一次调用多个协议。

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
}
func print(celebrator: stname & stage) {
   print("\(celebrator.name) is\(celebrator.age) years old")
}
let studname=Person(name: "Priya", age: 21)
print(studname)

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

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

运行上述程序时,我们得到以下输出-

Person(name: "Priya", age: 21)
Person(name: "Rehan", age: 29)
Person(name: "Roshan", age: 19)

协议一致性

协议一致性由" 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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

左耳听风 -〔陈皓〕

算法面试通关40讲 -〔覃超〕

苏杰的产品创新课 -〔苏杰〕

性能工程高手课 -〔庄振运〕

检索技术核心20讲 -〔陈东〕

OAuth 2.0实战课 -〔王新栋〕

张汉东的Rust实战课 -〔张汉东〕

全链路压测实战30讲 -〔高楼〕

技术领导力实战笔记 2022 -〔TGO 鲲鹏会〕

好记忆不如烂笔头。留下您的足迹吧 :)