且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

来自Objective-C协议的Swift扩展

更新时间:2022-03-24 22:33:27

问题是此Objective-C声明是非法的:

The problem is that this Objective-C declaration is illegal:

@protocol BSWeatherMapViewDelegate<MKMapViewDelegate>
@optional 
- (MKAnnotationView *)mapView:(BSWeatherMapView *)mapView viewForAnnotation:(id<MKAnnotation >)annotation;
@end

非法之处在于MKMapViewDelegate已经声明了一个名为 mapView:viewForAnnotation:的方法,但是具有不同的第一个参数类型.Objective-C中没有重载,因此无法区分MKMapViewDelegate mapView:viewForAnnotation:和BSWeatherMapViewDelegate mapView:viewForAnnotation:.如果同一个应用尝试同时实现这两个应用,则运行时将无法知道哪个是哪个.

The illegality is that MKMapViewDelegate already declares a method called mapView:viewForAnnotation:, but with a different first parameter type. There is no overloading in Objective-C, so it is impossible to distinguish between the MKMapViewDelegate mapView:viewForAnnotation: and the BSWeatherMapViewDelegate mapView:viewForAnnotation:. If the same app were to try to implement both, the runtime would have no way of knowing which is which.

只要您不尝试实现这两种方法,Objective-C编译器就不会阻止您.它会发出警告,但不会出现错误.(您在用Objective-C编写应用程序时,大概是无视了该警告;但这是一个错误,因为它会使您发现自己已经遇到麻烦了.)尝试同时实现这两种方法,您将遇到重复声明"的编译错误.

The Objective-C compiler doesn't actually stop you as long as you don't try to implement both methods; it warns but it does not error. (You, while writing your app in Objective-C, have presumably been blithely ignoring the warning; but that was a mistake, as it would have clued you in to the fact that you were already in trouble.) If you had tried to implement both, you would have gotten a "duplicate declaration" compile error.

但是由于 允许超载而使 能够分辨出它们之间的区别的Swift编译器更加主动,阻止了您实现 >其中.因此,您可以从不在Swift端实现它们中的任何一个.

But the Swift compiler, which can tell the difference between them because it does permit overloading, is more proactive and stops you from implementing either of them. Thus, you can never implement either of them on the Swift side.

因此,您的选择是:

  • 放弃使用该库,因为它有问题.

  • Abandon use of this library, as it is faulty.

将库修复为合法(假设您有权访问源).例如,更改BSWeatherMapViewDelegate方法的名称,无论它在哪里出现.

Fix the library to be legal (assuming you have access to the source). For example, change the name of the BSWeatherMapViewDelegate method wherever it occurs.

仅在Objective-C中实现这些委托方法,而不是在Swift中实现.

Implement these delegate methods only in Objective-C, not in Swift.