簡體   English   中英

如何讓2個不相關的Swift對象知道如何執行相同的功能

[英]How to get 2 unrelated Swift objects to know how to do the same sets of function

在任何人說繼承之前..首先聽聽我。

我有2個完全不相關的視圖控制器。 它們每個都有一個MKMapView 我希望它們都遵循並實現相同的委托方法。

例如,我都想實現:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let polyline = overlay as! MKPolyline
        let renderer = MKPolylineRenderer(polyline: polyline)
        renderer.strokeColor = UIColor.red
        renderer.lineWidth = 4
        return renderer
    }

同樣,這兩個視圖控制器完全無關,所以我不想創建基類。 實際上,這兩個視圖控制器已經從各自的繼承層次結構繼承。

使用協議和默認實現。

protocol SomeMapFunctions {
    var mapView : MKMapView? { get }

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer
}

extension SomeMapFunctions {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let polyline = overlay as! MKPolyline
        let renderer = MKPolylineRenderer(polyline: polyline)
        renderer.strokeColor = UIColor.red
        renderer.lineWidth = 4
        return renderer
    }
}

class VC1 : UIViewController, SomeMapFunctions {
    var mapView : MKMapView?
}

class VC2 : UIViewController, SomeMapFunctions {
    var mapView : MKMapView?
}

如圖所示,默認實現所需的任何公共屬性也可以放入協議中。

一種解決方案可能是:

protocol CommonStuff {
   func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer 
}

extension CommonStuff where Self: UIViewController {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let polyline = overlay as! MKPolyline
        let renderer = MKPolylineRenderer(polyline: polyline)
        renderer.strokeColor = UIColor.red
        renderer.lineWidth = 4
        return renderer
    }
}

然后,兩個視圖控制器采用該協議將為它們提供相同的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM