简体   繁体   English

如何使非类类型符合类协议?

[英]How to make a non-class type conform to a class protocol?

For example, how can I make MapView, which is a 'struct' type conform to CLLocationManagerDelegate which requires a 'class' type for its protocol?例如,我怎样才能让 MapView(一个“结构”类型)符合 CLLocationManagerDelegate,它的协议需要一个“类”类型?

Code Block 
struct  MapView: UIViewRepresentable, CLLocationManagerDelegate {
    var coordinate: CLLocationCoordinate2D
    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }
    func updateUIView(_ uiView: MKMapView, context: Context) {
        let span = MKCoordinateSpan(latitudeDelta: 0.0019, longitudeDelta: 0.0019)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        uiView.setRegion(region, animated: true)
        uiView.mapType = .hybridFlyover
    }
}

The protocol for CLLocationManagerDelegate has been set as type class, and it's made by apple. CLLocationManagerDelegate 的协议已经设置为类型类,它是由苹果制作的。 Thus we can't change it.因此我们无法改变它。 Any reason you want to make it a struct rather than a class?你有什么理由想把它变成一个结构而不是一个类?

As others have noted, you can't, but in this case it's particularly important why.正如其他人所指出的,你不能,但在这种情况下,为什么特别重要。 Views are created and destroyed all the time;视图一直在创建和销毁; they're just values.他们只是价值观。 A delegate is a specific object.委托是一个特定的对象。 There's no way for a View to play the role of a delegate.视图无法扮演委托的角色。 The CLLocationManager would wind having one copy, and you'd be looking at another copy in your view hierarchy. CLLocationManager 将拥有一个副本,而您将在视图层次结构中查看另一个副本。 Instead, you need to create some other object, most likely an ObservableObject that tracks whatever location information you need, and the Views will observe that.相反,您需要创建一些其他对象,很可能是一个ObservableObject来跟踪您需要的任何位置信息,而视图将观察到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM