代码之家  ›  专栏  ›  技术社区  ›  Alex Stone

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

  •  0
  • Alex Stone  · 技术社区  · 8 年前

    我有一个用Objective-C编写的遗留代码库,我正在添加一个用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?
        }
        }
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   Enea Dume    8 年前
    [MyClass conformsToProtocol:@protocol(MyProtocol)];
    

    Apple Docs 你可以用 conformsToProtocol: 它返回一个布尔值,指示接收器是否符合给定的协议。


    @protocol MyProtocol
    - (void)helloWorld;
    @end
    
    @interface MyClass : NSObject <MyProtocol>
    @end
    

    将暴露为:

    console.log(MyClass.conformsToProtocol(MyProtocol)); 
    
    var instance = MyClass.alloc().init();
    console.log(instance.conformsToProtocol(MyProtocol))
    
        2
  •  2
  •   vacawama    8 年前

    确保你 #import 您的协议定义文件 <ProjectName>-Bridging-Header.h 文件:

    #import "OBJCLocationObserver.h"
    

    如果你的签名不匹配,你应该会看到错误信息。

    也可以使用Xcode . 类型:

    public func didUpdateLocation
    

    和 自动完成 建议:

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

    这与你所拥有的不同,也解释了为什么它不起作用。


    正如@MartinR在对另一个问题的评论中所建议的那样:

    转到定义协议的头文件,然后选择 左上角“相关项目”弹出窗口中的“生成界面” 必须实施。