Swift 协议
协议为方法、属性和其他需求功能提供了一个蓝图。它只是描述了方法或属性的轮廓,而不是具体实现。方法和属性的具体实现可以通过定义类、函数和枚举来完成。遵循协议就是满足协议需求的方法或属性。
语法
协议的语法与类、结构体和枚举类似 –
protocol SomeProtocol {
// protocol definition
}
协议在类、结构体或枚举类型名称之后声明。也可以声明单个和多个协议。如果定义了多个协议,则必须用逗号隔开。
struct SomeStructure: Protocol1, Protocol2 {
// structure definition
}
当必须为超类定义协议时,协议名称应该紧跟超类名称后面,使用逗号分隔。
class SomeClass: SomeSuperclass, Protocol1, Protocol2 {
// class definition
}
属性和方法要求
协议用于指定特定类类型的属性或实例属性。它仅指定类型或实例属性,而不指定其是存储属性还是计算属性。此外,它用于指定属性是否可“获得”或“设置”。
属性要求通过“var”关键字声明为属性变量。{get set}用于在类型声明后声明可获取和可设置的属性。可获取的属性在其类型声明后通过{get}属性进行说明。
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)
当我们在playground中运行上述程序时,我们会得到以下结果−
98
true
false
Swift 4 Protocols
Swift 4
方法变异要求
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()
当我们在playground上运行上面的程序时,我们得到以下结果−
Wednesday
初始化器要求
Swing允许用户初始化协议以遵循与普通初始化器类似的类型的一致性。
语法
protocol SomeProtocol {
init(someParameter: Int)
}
例如
protocol tcpprotocol {
init(aprot: Int)
}
协议初始化需求的类实现
指定的或便利的初始化方法允许用户通过保留的 ‘required’ 关键字来初始化一个协议以符合其标准。
class SomeClass: SomeProtocol {
required init(someParameter: Int) {
// initializer implementation statements
}
}
protocol tcpprotocol {
init(aprot: Int)
}
class tcpClass: tcpprotocol {
required init(aprot: Int) {
}
}
通过’required’修饰符,在所有子类中确保协议的一致性,用于显式或继承实现。
当子类重写其超类的初始化要求时,使用’override’修饰符关键字进行指定。
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 print = subClass(no1: 30, no2: 50)
print("res is: \(res.no1)")
print("res is: \(print.no1)")
print("res is: \(print.no2)")
当我们使用playground运行以上程序时,我们得到以下结果:
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}))
当我们在Playground中运行上述程序时,我们将获得以下结果−
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)
当我们使用 playground 运行以上程序时,我们得到以下结果 –
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 print = subClass(no1: 30, no2: 50)
print("res is: \(res.no1)")
print("res is: \(print.no1)")
print("res is: \(print.no2)")
当我们在playground上运行上面的程序时,我们会得到以下结果 −
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)
当我们在playground上运行上述程序时,我们得到以下结果 –
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")
}
}
当我们在playground中运行上面的程序时,我们会得到以下结果−
Area is 12.5663708
Area is 198.0
Rectangle area is not defined