前言
多繼承和多重代理在swift的語言層面上是不支持的,但我們有時(shí)會(huì)遇到這樣的問題:
面對(duì)第一種情況,最好的解決方法是,B1和C1的公共方法專門封裝到一個(gè)地方,需要的時(shí)候就調(diào)用一下,多繼承就是一個(gè)最好的解決方案.
1. 多繼承
1. 實(shí)現(xiàn)過程
swift中的類可以遵守多個(gè)協(xié)議,但是只可以繼承一個(gè)類,而值類型(結(jié)構(gòu)體和枚舉)只能遵守單個(gè)或多個(gè)協(xié)議,不能做繼承操作.
多繼承的實(shí)現(xiàn):協(xié)議的方法可以在該協(xié)議的extension中實(shí)現(xiàn)
protocol Behavior { func run()}extension Behavior { func run() { print("Running...") }}struct Dog: Behavior {}let myDog = Dog()myDog.run() // Running...
無論是結(jié)構(gòu)體還是類還是枚舉都可以遵守多個(gè)協(xié)議,所以要實(shí)現(xiàn)多繼承,無非就是多遵守幾個(gè)協(xié)議的問題.
下面舉個(gè)例子.
2. 通過多繼承為UIView擴(kuò)展方法
// MARK: - 閃爍功能protocol Blinkable { func blink()}extension Blinkable where Self: UIView { func blink() { alpha = 1 UIView.animate( withDuration: 0.5, delay: 0.25, options: [.repeat, .autoreverse], animations: { self.alpha = 0 }) }}// MARK: - 放大和縮小protocol Scalable { func scale()}extension Scalable where Self: UIView { func scale() { transform = .identity UIView.animate( withDuration: 0.5, delay: 0.25, options: [.repeat, .autoreverse], animations: { self.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) }) }}// MARK: - 添加圓角protocol CornersRoundable { func roundCorners()}extension CornersRoundable where Self: UIView { func roundCorners() { layer.cornerRadius = bounds.width * 0.1 layer.masksToBounds = true }}extension UIView: Scalable, Blinkable, CornersRoundable {} cyanView.blink() cyanView.scale() cyanView.roundCorners()
這樣,如果我們自定義了其他View,只需要放大和縮小效果,遵守Scalable協(xié)議就可以啦!
3. 多繼承鉆石問題(Diamond Problem),及解決辦法
請(qǐng)看下面代碼
protocol ProtocolA { func method()}extension ProtocolA { func method() { print("Method from ProtocolA") }}protocol ProtocolB { func method()}extension ProtocolB { func method() { print("Method from ProtocolB") }}class MyClass: ProtocolA, ProtocolB {}
此時(shí)ProtocolA和ProtocolB都有一個(gè)默認(rèn)的實(shí)現(xiàn)方法method(),由于編譯器不知道繼承過來的method()方法是哪個(gè),就會(huì)報(bào)錯(cuò).
注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到IOS開發(fā)頻道。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注