協議(Protocols)為方法,屬性和其他需求功能提供了藍圖。 它為方法或屬性骨架而不是實現。 通過定義類,函數和枚舉,可以進一步完成方法和屬性的實現。 協議的一致性滿足了協議要求的方法或屬性。
語法
協議也遵循與類,結構和枚舉類似的語法 -
protocol SomeProtocol {
// protocol definition
}
協議在類,結構或枚舉類型名稱之後聲明。 單個和多個協議聲明也是可以的。 如果定義了多個協議,則必須用逗號分隔。
struct SomeStructure: Protocol1, Protocol2 {
// structure definition
}
當要為超類定義協議時,協議名稱應使用逗號跟隨超類名稱。
class SomeClass: SomeSuperclass, Protocol1, Protocol2 {
// class definition
}
屬性和方法要求
協議用於指定特定的類類型屬性或實例屬性。 它只是單獨指定類型或實例屬性,而不是指定它是存儲屬性還是計算屬性。 此外,它還用於指定屬性是gettable
或settable
。
屬性需求由var
關鍵字聲明為屬性變數。 {get/set}
用於在類型聲明後聲明gettable
和settable
屬性。參考以下一個示例代碼 -
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) {
}
}
當使用playground 運行上述程式時,得到以下結果 -
Wednesday
通過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: "zaixian", age: 21)
print(studname)
let stud = Person(name: "Maxsu", age: 29)
print(stud)
let student = Person(name: "Roshan", age: 19)
print(student)
當使用playground 運行上述程式時,得到以下結果 -
Person(name: "zaixian", age: 21)
Person(name: "Maxsu", 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