Swift基礎(chǔ)-協(xié)議

協(xié)議的格式

  • 協(xié)議的定義方式與類(lèi),結(jié)構(gòu)體,枚舉的定義都非常相似
protocol SomeProtocol {
    // 協(xié)議方法
}
  • 遵守協(xié)議的格式
class SomeClass: SomeSuperClass, FirstProtocol,             AnotherProtocol {
    // 類(lèi)的內(nèi)容
    // 實(shí)現(xiàn)協(xié)議中的方法
}

協(xié)議的基本使用

  • 定義協(xié)議和遵守協(xié)議
// 1.定義協(xié)議
protocol SportProtocol {
    func playBasketball()
    func playFootball()
}

// 2.遵守協(xié)議
// 注意:默認(rèn)情況下在swift中所有的協(xié)議方法都是必須實(shí)現(xiàn)的,如果不實(shí)現(xiàn),則編譯器會(huì)報(bào)錯(cuò)
class Person : SportProtocol {
    var name : String?
    var age : Int = 0

    // 實(shí)現(xiàn)協(xié)議中的方法
    func playBasketball() {
        print("人在打籃球")
    }

    func playFootball() {
        print("人在踢足球")
    }
}
  • 協(xié)議之間的繼承
protocol CrazySportProtocol {
    func jumping()
}

protocol SportProtocol : CrazySportProtocol {
    func playBasketball()
    func playFootball()
}

代理設(shè)計(jì)模式

  • 協(xié)議繼承用于代理設(shè)計(jì)模式
protocol BuyTicketProtocol {
    func buyTicket()
}

class Person {
    // 1.定義協(xié)議屬性
    var delegate : BuyTicketProtocol

    // 2.自定義構(gòu)造函數(shù)
    init (delegate : BuyTicketProtocol) {
        self.delegate = delegate
    }

    // 3.行為
    func goToBeijing() {
        delegate.buyTicket()
    }
}


class HuangNiu: BuyTicketProtocol {
    func buyTicket() {
        print("買(mǎi)了一張火車(chē)票")
    }
}

let p = Person(delegate: HuangNiu())
p.goToBeijing()
  • 協(xié)議中方法的可選
    • swift不支持optional,需要通過(guò)oc來(lái)設(shè)置協(xié)議的可選方法
// 1.定義協(xié)議
@objc
protocol SportProtocol {
    func playBasketball()

    optional func playFootball()
}

// 2.遵守協(xié)議
class Person : SportProtocol {
    var name : String?
    var age : Int = 0

    // 實(shí)現(xiàn)協(xié)議中的方法
    @objc func playBasketball() {
        print("人在打籃球")
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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