protocol (Swift3.x)

Swift中 protocol的學(xué)習(xí)

//擴(kuò)展標(biāo)準(zhǔn)庫/定義屬于個人的協(xié)議的學(xué)習(xí)

//--------------- SomeProtocol ---------------//

protocol SomeProtocol {

? ? ? ? //1.

? ? ? ? ?func f()

? ? ? ? ? //2. 用關(guān)鍵字 'static' 來聲明類方法

? ? ? ? ? ?static func someTypeMethod(_ type: String)

? ? ? ? ? //3. 構(gòu)造器方法

? ? ? ? ? ?init(someParameter: Int)

}

//定義Wjq類, 并遵守 'SomeProtocol' 協(xié)議

//實現(xiàn)協(xié)議的類型除了 class 外,還可以是 struct 或 enum。

/*-----實現(xiàn)協(xié)議的方式一 -----*/

class Wjq: SomeProtocol{

//1.

? ? ? ? ? ?func f() { ? ? ? ? ?print("定義類, 并直接在當(dāng)前類遵守 'SomeProtocol' 協(xié)議") ? }

//2. 如果實現(xiàn)該協(xié)議的類型是class 類型, 則在實現(xiàn)類中除了用static 來修飾類方法外, 還可以用class來修飾

//這里也可以用 static 修飾,區(qū)別是 static 修飾的屬性或方法不能被子類復(fù)寫,class 修飾的可以被子類復(fù)寫

? ? ? ? ? class func someTypeMethod(_ type: String) {

? ? ? ? ? ? ? ? print("type Method")

? ? ? ? }

//3. 遵循協(xié)議的類型實現(xiàn)指定的構(gòu)造器:

//注意: 在符合協(xié)議的類中實現(xiàn)構(gòu)造器,必須在構(gòu)造器實現(xiàn)前加上 required 修飾符。使用 required 修飾符可以確保所有子類也必須提供此構(gòu)造器實現(xiàn),從而也能符合協(xié)議。 如果類已經(jīng)被標(biāo)記為 final,那么不需要在協(xié)議構(gòu)造器的實現(xiàn)中使用 required 修飾符,因為 final 類不能有子類.

? ? ? ? required init(someParameter: Int) {

? ? ? ? ? ? //初始化

? ? ? ? }

}

/*-----實現(xiàn)協(xié)議的方式二 定義類, 通過 'extension(擴(kuò)展)' 實現(xiàn)協(xié)議-----*/

/*class Wjq{

}

extension Wjq: SomeProtocol {

? ? ? ? ? ? func f() {

? ? ? ? ? ? ? ?print("定義類, 通過 'extension(擴(kuò)展)' 實現(xiàn)協(xié)議")

? ? ? ? ? ?}

}

*/

//子類

class wj: Wjq {

? ? ? ? ? ? override func f() {

? ? ? ? ? ? ? print("當(dāng)子類復(fù)寫父類的方法或計算屬性時才需要用 override 修飾")

? ? ? ? ?}

}

//---------------? MyProtocol ---------------//

//協(xié)議中聲明屬性和方法

protocol MyProtocol {

? ? ? ? ? ? var prop: Int { get set } // { set get } 來表示屬性是可讀可寫的

? ? ? ? ? ? ?var propertyWithImplementation: String { get } //用 { get } 來表示屬性是只讀的

? ? ? ? ? ? func foo()

? ? ? ? ? ? //注意: 協(xié)議里面聲明的屬性和方法一定是抽象的,不能有實現(xiàn),由符合協(xié)議的類型來提供所有屬性和方法的實現(xiàn)。

}

//MARK: -- 通過擴(kuò)展協(xié)議達(dá)到為協(xié)議中的'屬性'和'方法'提供默認(rèn)實現(xiàn)的目的

extension MyProtocol{

? ? ? var propertyWithImplementation: String {return "通過擴(kuò)展協(xié)議使得'屬性' 有默認(rèn)實現(xiàn)"}

? ? ? func foo()? { ? print(prop) ? }

? ? ? //在 'extension' 中添加 'MyProtocol' 協(xié)議中沒有定義過的屬性和方法

? ? ? ? ? ?var exceed: Double { return 23 }

? ? ? ?func isExceed() -> Bool { ? return prop > 30 ?}

}

class MyClass: MyProtocol {

var prop: Int = 20

}

//---------------? TextRepresentable? --------------//

protocol TextRepresentable {

var textualDescription: String { get }

}

// 實現(xiàn)協(xié)議的關(guān)鍵字 --> struct

struct Hamster: TextRepresentable {

var name: String

var textualDescription: String{

return "A hamster named \(name)"

}

}

//在擴(kuò)展協(xié)議的時候,還可以指定一些限制條件,只有遵循協(xié)議的類型滿足這些限制條件時,才能獲得協(xié)議擴(kuò)展提供的默認(rèn)實現(xiàn)。

//這里擴(kuò)展了 Swift 標(biāo)準(zhǔn)庫中的 Collection 協(xié)議,但是限制只適用于集合中的元素遵循了 TextRepresentable 協(xié)議的情況。 因為 Swift 中 Array 符合 Collection 協(xié)議,而 Hamster 類型又符合 TextRepresentable 協(xié)議,所以 hamsters 可以使用 textualDescription 屬性得到數(shù)組內(nèi)容的文本表示。

extension Collection where Iterator.Element: TextRepresentable{

var textualDescription: String {

let itemsAsText = self.map { $0.textualDescription }

return "[" + itemsAsText.joined(separator: ", ") + "]"

}

}


//------------------協(xié)議中可以定義可變方法-----------------//

protocol Togglable {

? ? ? ? ?mutating func toggle()

}

enum OnOffSwitch: Togglable {

? ? ? ? case off, on

? ? ? ?mutating func toggle() {

? ? ? ? ? ?switch self {

? ? ? ? ? case .off:

? ? ? ? ?self = .on

? ? ? ? ?case .on:

? ? ? ? self = .off

? ? ? ?}

? ? }

}


//上面展示了實現(xiàn)協(xié)議的三種類型 class , struct , enum。

//如果想要限制協(xié)議只能被 Class 類型遵循,而結(jié)構(gòu)體或枚舉不能遵循該協(xié)議。 我們還可以讓協(xié)議繼承 AnyObject 來實現(xiàn)


protocol onlyClassImplementation: AnyObject {

func onlyClass()

}

class onlyClass: onlyClassImplementation {

func onlyClass() {

//

}

}

//報錯

//struct cla:? onlyClassImplementation {

//

//}

//------------? 協(xié)議組合? ---------------------//

protocol Name {

var name: String { get }

}

protocol Age {

var age: Int { get }

}

struct Pers: Name, Age {

var name: String

var age: Int

}

//------------? 協(xié)議還可以與類進(jìn)行組合? ---------------------//

class Location {

var latitude: Double

var longitude: Double

init(latitude: Double, longitude: Double) {

self.latitude = latitude

self.longitude = longitude

}

}

class City: Location, Name {

var name: String

init(name: String, latitude: Double, longitude: Double) {

self.name = name

super.init(latitude: latitude, longitude: longitude)

}

}

/*

協(xié)議還可以與類進(jìn)行組合

func beginConcert(in location: Location & Name) {

print("Hello, \(location.name)!")

}

let seattle = City(name: "Seattle", latitude: 47.6, longitude: -122.3)

beginConcert(in: seattle)

*/


//------------? optional 可選協(xié)議? ---------------------//

@objc protocol CounterDataSource {

@objc optional func incrementForCount(count: Int) -> Int

@objc optional var fixedIncrement: Int { get }

//注意:標(biāo)記為 @objc 的 protocol 只能被 class 實現(xiàn),不能被 struct 和 enum 類型實現(xiàn),而且實現(xiàn)它的 class 中的方法也必須被標(biāo)注為 @objc,或者整個類就是繼承自 NSObject。

}


//------------? delegate ---------------------//

protocol RentHouserDelegate{

func rent(_ name:String)

}

class Tenant {

var name = "ii"

var delegate: RentHouserDelegate?

func rentHouse() {

delegate?.rent(name)

}

}

class Intermediary: RentHouserDelegate {

var name = "aa"

func rent(_ name: String) {

print("\(name) 請 \(self.name) 幫她租一套房子");

}

}


//檢查協(xié)議一致性, 可以通過 is ,? as? ,? as 來檢查某個實例是否符合某個協(xié)議:

class view: ViewController,Name,Age {

var age: Int = 0

var name: String = ""

override func viewDidLoad() {

var lightSwitch = OnOffSwitch.off

lightSwitch.toggle()

// lightSwitch 現(xiàn)在的值為 .On

//協(xié)議組合

func wishHappyBirthday(to celebrator: Name & Age) {

print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!")

}

let birthdayPerson = Pers(name: "Malcolm", age: 21)

wishHappyBirthday(to: birthdayPerson)

// Prints "Happy birthday, Malcolm, you're 21!"

/*? delegate? */

let person = Tenant()

person.delegate = Intermediary()

person.rentHouse()

}

}


Demo:?

github.com/wangjianquan/Swift3.x_basics.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容