简体   繁体   English

iOS11 Swift 4-如何检查Swift类是否符合Objective-C中定义的协议?

[英]iOS11 Swift 4 - how to check if Swift class conforms to protocol defined in Objective-C?

I have a legacy code base with code written in Objective-C. 我有一个用Objective-C编写的代码的旧代码库。 I'm adding a new class written in Swift which has to conform to existing protocols defined in Objective-C. 我要添加一个用Swift编写的新类,该类必须符合Objective-C中定义的现有协议。

How can I make sure my Swift class correctly implements methods defined in Objective-C protocol? 如何确保我的Swift类正确实现了Objective-C协议中定义的方法?

//In Obj-C
    @protocol OBJCLocationObserver <NSObject>
    - (void)didUpdateLocationWithModel:(nullable Model *)locationModel
                       lastLocation:(CLLocationCoordinate2D)lastLocation;
    @end


//In Swift

    extension SwiftLocationManager : OBJCLocationObserver
    {
        public func didUpdateLocation(with model: Model?, lastLocation: CLLocationCoordinate2D) {
    // How to verify this function signature is actually conforming to the Obj-C protocol and is not a new method?
    }
    }

Make sure you #import your protocol definition file into the <ProjectName>-Bridging-Header.h file: 确保您将协议定义文件#import<ProjectName>-Bridging-Header.h文件中:

#import "OBJCLocationObserver.h"

And then you should see error messages if your signature does not match. 然后,如果您的签名不匹配,您应该看到错误消息。

You can also use Xcode Auto Completion . 您还可以使用Xcode 自动完成 Type: 类型:

public func didUpdateLocation

and Auto Complete suggests: 自动完成建议:

public func didUpdateLocation(withModel Model?, lastLocation: CLLocationCoordinate2D)

which is different than what you have and explains why it isn't working. 这与您现有的有所不同,并解释了为什么它不起作用。


Here is another way to get the interface: 这是获取界面的另一种方法:

As @MartinR suggested on a comment to another question: 正如@MartinR在对另一个问题的评论中所建议的那样:

Go to the header file where the protocol is defined, and choose "Generated Interface" from the "Related Items" popup in the top-left corner. 转到定义协议的头文件,然后从左上角的“相关项目”弹出窗口中选择“生成的接口”。 That will show you the exact Swift method signature that you have to implement. 这将向您显示您必须实现的确切Swift方法签名。

[MyClass conformsToProtocol:@protocol(MyProtocol)];

According to Apple Docs you can use conformsToProtocol: which returns a Boolean value that indicates whether the receiver conforms to a given protocol. 根据Apple Docs的说明,您可以使用conformsToProtocol:返回一个布尔值,该值指示接收方是否符合给定的协议。


Example

@protocol MyProtocol
- (void)helloWorld;
@end

@interface MyClass : NSObject <MyProtocol>
@end

Will be exposed as: 将被暴露为:

console.log(MyClass.conformsToProtocol(MyProtocol)); 

var instance = MyClass.alloc().init();
console.log(instance.conformsToProtocol(MyProtocol))

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

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