[英]How to get 2 unrelated Swift objects to know how to do the same sets of function
Before anyone says inheritance.. hear me out first. 在任何人说继承之前..首先听听我。
I have 2 totally unrelated view controllers. 我有2个完全不相关的视图控制器。 They each have an MKMapView
. 它们每个都有一个MKMapView
。 I would like both of them to conform to and implement the same delegate methods. 我希望它们都遵循并实现相同的委托方法。
For example, I want both to implement: 例如,我都想实现:
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
}
Again, these 2 view controllers aren't related at all, so I don't want to make a base class. 同样,这两个视图控制器完全无关,所以我不想创建基类。 As a matter of fact, these 2 view controllers are already inheriting from their respective inheritance hierarchy. 实际上,这两个视图控制器已经从各自的继承层次结构继承。
Use a protocol and a default implementation. 使用协议和默认实现。
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?
}
As shown, any common properties that are necessary for the default implementations can be put into the protocol as well. 如图所示,默认实现所需的任何公共属性也可以放入协议中。
One solution could be: 一种解决方案可能是:
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
}
}
Then, adopting the protocol by both view controllers would provide them the same behaviour. 然后,两个视图控制器采用该协议将为它们提供相同的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.