news 2026/4/19 3:31:26

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Swift Protocols 怎么用?协议在 Swift 中如何定义和实现?

协议为方法、属性和其他要求功能提供了一个蓝图。它仅被描述为方法或属性的骨架,而不是实现。方法和属性的实现可以通过定义 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
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/19 3:29:36

用100道题拿下你的算法面试(矩阵篇-2):求转置矩阵

一、面试问题给定一个二维矩阵 mat [][]&#xff0c;计算其转置矩阵。矩阵的转置是通过将原矩阵的所有行转换为列、所有列转换为行得到的。示例 1&#xff1a;输入以下矩阵&#xff1a;mat[][] [[1, 1, 1, 1],[2, 2, 2, 2],[3, 3, 3, 3],[4, 4, 4, 4] ]得到以下输出&#xff1…

作者头像 李华
网站建设 2026/4/19 3:24:19

告别996!用Vol框架+Vue3+.Net6,30分钟搞定一个带权限的后台管理系统

30分钟构建企业级后台&#xff1a;Vol框架Vue3与.NET 6的高效协作指南 深夜十一点的办公室&#xff0c;李工盯着屏幕上重复的CRUD代码和不断闪烁的钉钉消息&#xff0c;第N次修改着产品经理临时增加的需求。这种场景对许多中小企业的开发者而言再熟悉不过——权限管理、表单验…

作者头像 李华
网站建设 2026/4/19 3:17:06

ILSpy命令行批量反编译:高效处理多个.NET程序集的终极指南

ILSpy命令行批量反编译&#xff1a;高效处理多个.NET程序集的终极指南 【免费下载链接】ILSpy .NET Decompiler with support for PDB generation, ReadyToRun, Metadata (&more) - cross-platform! 项目地址: https://gitcode.com/gh_mirrors/il/ILSpy ILSpy作为业…

作者头像 李华
网站建设 2026/4/19 3:13:28

基于Docker + Jenkins + GitLab打造一站式CI-CD流水线

在当今快速迭代的软件开发环境中&#xff0c;高效的CI/CD流水线已成为团队提升交付质量的关键。基于Docker、Jenkins和GitLab的一站式解决方案&#xff0c;通过容器化隔离、自动化构建和代码托管协同&#xff0c;为开发者提供了从提交到部署的完整闭环。本文将深入解析这一技术…

作者头像 李华