Swift基礎-協議

協議的格式

  • 協議的定義方式與類,結構體,枚舉的定義都非常相似
protocol SomeProtocol {
    // 協議方法
}
  • 遵守協議的格式
class SomeClass: SomeSuperClass, FirstProtocol,             AnotherProtocol {
    // 類的內容
    // 實現協議中的方法
}

協議的基本使用

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

// 2.遵守協議
// 注意:默認情況下在swift中所有的協議方法都是必須實現的,如果不實現,則編譯器會報錯
class Person : SportProtocol {
    var name : String?
    var age : Int = 0

    // 實現協議中的方法
    func playBasketball() {
        print("人在打籃球")
    }

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

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

代理設計模式

  • 協議繼承用于代理設計模式
protocol BuyTicketProtocol {
    func buyTicket()
}

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

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

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


class HuangNiu: BuyTicketProtocol {
    func buyTicket() {
        print("買了一張火車票")
    }
}

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

    optional func playFootball()
}

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

    // 實現協議中的方法
    @objc func playBasketball() {
        print("人在打籃球")
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容