深入解析Swift語言中的協(xié)議
協(xié)議為方法,屬性和其他要求的功能提供了一個(gè)藍(lán)本。它只是描述了方法或?qū)傩缘墓羌?,而不是?shí)現(xiàn)。方法和屬性實(shí)現(xiàn)還可以通過定義類,函數(shù)和枚舉完成。協(xié)議的一致性是指方法或?qū)傩詽M足協(xié)議的要求。
語法
協(xié)議也遵循類似類,結(jié)構(gòu)和枚舉的語法:
protocol SomeProtocol {
// protocol definition
}
協(xié)議在類,結(jié)構(gòu)或枚舉類型命名聲明。單個(gè)和多個(gè)協(xié)議的聲明也是可以的。如果多個(gè)協(xié)議規(guī)定,它們必須用逗號(hào)分隔。
struct SomeStructure: Protocol1, Protocol2 {
// structure definition
}
當(dāng)一個(gè)協(xié)議在超類中定義,協(xié)議名稱應(yīng)遵循命名在超類之后。
class SomeClass: SomeSuperclass, Protocol1, Protocol2 {
// class definition
}
屬性和方法的要求
協(xié)議用于指定特定類型的屬性或?qū)傩缘膶?shí)例。它僅指定類型或?qū)嵗龑傩詥为?dú)而不是指定它是否是一個(gè)存儲(chǔ)或計(jì)算屬性。另外,它是用來指定的屬性是否為“可獲取'或'可設(shè)置”。
屬性要求由 “var” 關(guān)鍵字作為屬性變量聲明。 {get set} 使用它們類型聲明后聲明屬性可獲取和可設(shè)置。 可獲取是由它們的類型{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 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"
studdet.marks = 98
studdet.markssecured()
println(studdet.marks)
println(studdet.result)
println(studdet.present)
println(studdet.subject)
println(studdet.stname)
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果。
98 true false Swift Protocols Swift
不同變形方法要求
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
println("Sunday")
case mon:
self = mon
println("Monday")
case tue:
self = tue
println("Tuesday")
case wed:
self = wed
println("Wednesday")
case mon:
self = thurs
println("Thursday")
case tue:
self = fri
println("Friday")
case sat:
self = sat
println("Saturday")
default:
println("NO Such Day")
}
}
}
var res = days.wed
res.print()
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果。
Wednesday
初始化程序要求
Swift 允許用戶初始化協(xié)議遵循類似于正常初始化類型的一致性。
語法
protocol SomeProtocol {
init(someParameter: Int)
}
示例
protocol tcpprotocol {
init(aprot: Int)
}
協(xié)議初始化程序要求類實(shí)現(xiàn)
指定或初始化便捷允許用戶初始化協(xié)議來預(yù)留“required”關(guān)鍵字,以符合其標(biāo)準(zhǔn)。
class SomeClass: SomeProtocol {
required init(someParameter: Int) {
// initializer implementation statements
}
}
protocol tcpprotocol {
init(aprot: Int)
}
class tcpClass: tcpprotocol {
required init(aprot: Int) {
}
}
協(xié)議一致性保證所有子類顯式或繼承實(shí)現(xiàn)“required”修辭符。
當(dāng)一個(gè)子類覆蓋其超類的初始化必須由“override”修飾符關(guān)鍵字指定。
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)
println("res is: \(res.no1)")
println("res is: \(print.no1)")
println("res is: \(print.no2)")
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果。
res is: 20 res is: 30 res is: 50
協(xié)議作為類型
相反,在協(xié)議執(zhí)行的功能被用作函數(shù),類,方法等類型。
協(xié)議可以訪問作為類型:
函數(shù),方法或初始化作為一個(gè)參數(shù)或返回類型
常量,變量或?qū)傩?/p>
數(shù)組,字典或其他容器作為項(xiàng)目
protocol Generator {
typealias members
func next() -> members?
}
var items = [10,20,30].generate()
while let x = items.next() {
println(x)
}
for lists in map([1,2,3], {i in i*5}) {
println(lists)
}
println([100,200,300])
println(map([1,2,3], {i in i*10}))
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果。
10 20 30 5 10 15 [100, 200, 300] [10, 20, 30]
添加協(xié)議一致性與擴(kuò)展
已有的類型可以通過和利用擴(kuò)展符合新的協(xié)議。新屬性,方法和下標(biāo)可以被添加到現(xiàn)有的類型在擴(kuò)展的幫助下。
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"
}
}
}
協(xié)議繼承
Swift 允許協(xié)議繼承其定義的屬性的屬性。它類似于類的繼承,但用逗號(hào)分隔列舉選擇多個(gè)繼承協(xié)議。
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(1)
}
}
class classb: result {
func print(target: classa) {
target.calc(5)
}
}
class student: classa {
var no1: Int = 10
func calc(sum: Int) {
no1 -= sum
println("Student attempted \(sum) times to pass")
if no1 <= 0 {
println("Student is absent for exam")
}
}
}
class Player {
var stmark: result!
init(stmark: result) {
self.stmark = stmark
}
func print(target: classa) {
stmark.print(target)
}
}
var marks = Player(stmark: student2())
var marksec = student()
marks.print(marksec)
marks.print(marksec)
marks.print(marksec)
marks.stmark = classb()
marks.print(marksec)
marks.print(marksec)
marks.print(marksec)
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果。
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
只有類協(xié)議
當(dāng)協(xié)議被定義,并且用戶想要定義協(xié)議與它應(yīng)該通過定義類第一后跟協(xié)議的繼承列表被添加的類。
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)
println("res is: \(res.no1)")
println("res is: \(print.no1)")
println("res is: \(print.no2)")
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果。
res is: 20 res is: 30 res is: 50
協(xié)議組合
Swift 允許多個(gè)協(xié)議在協(xié)議組合的幫助下調(diào)用一次。
語法
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: protocol<stname, stage>) {
println("\(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)
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果。
Priya is 21 years old Rehan is 29 years old Roshan is 19 years old
檢查協(xié)議一致性
協(xié)議一致性是 is 和 as 類似于類型轉(zhuǎn)換的操作符測試。
如果一個(gè)實(shí)例符合協(xié)議標(biāo)準(zhǔn),is運(yùn)算符如果失敗返回false ,否則返回true。
as? 版本是向下轉(zhuǎn)型操作符,返回協(xié)議的類型的可選值,并且如果該值是nil ,實(shí)例不符合該協(xié)議。
as 版是向下轉(zhuǎn)型操作符,強(qiáng)制向下轉(zhuǎn)型的協(xié)議類型并觸發(fā)一個(gè)運(yùn)行時(shí)錯(cuò)誤,如果向下轉(zhuǎn)型不會(huì)成功。
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 {
println("Area is \(objectWithArea.area)")
} else {
println("Rectangle area is not defined")
}
}
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果。
Area is 12.5663708 Area is 198.0 Rectangle area is not defined
相關(guān)文章
switch多選擇結(jié)構(gòu)、循環(huán)結(jié)構(gòu)示例詳解
這篇文章主要介紹了switch多選擇結(jié)構(gòu)、循環(huán)結(jié)構(gòu),本文結(jié)合示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-12-12Swift實(shí)現(xiàn)簡單計(jì)算器項(xiàng)目
這篇文章主要為大家詳細(xì)介紹了Swift實(shí)現(xiàn)簡單計(jì)算器項(xiàng)目,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01Swift使用SnapKit模仿Kingfisher第三方擴(kuò)展優(yōu)化
這篇文章主要為大家介紹了Swift?SnapKit模仿Kingfisher第三方擴(kuò)展優(yōu)化示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09Swift開發(fā)之UITableView狀態(tài)切換效果
這篇文章主要介紹了Swift開發(fā)之UITableView狀態(tài)切換效果的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-08-08iOS Swift UICollectionView橫向分頁滾動(dòng),cell左右排版問題詳解
UICollectionView是iOS中比較常見的一個(gè)控件,這篇文章主要給大家介紹了關(guān)于iOS Swift UICollectionView橫向分頁滾動(dòng),cell左右排版問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12