Importing a Swift protocol in Objective-C class

后端 未结 5 1851
耶瑟儿~
耶瑟儿~ 2020-12-23 00:11

I try to import a Swift Protocol named AnalyticProtocol into an Objective-C class named AnalyticFactory.

protocol AnalyticProtocol
         


        
5条回答
  •  -上瘾入骨i
    2020-12-23 00:59

    We can use swift protocols in Objective C with few changes to the code. Also, @objc declared protocols let you have optional and required methods without default implementations. It comes with pros and cons.

    We could actually re-name the protocol name to a more descriptive when using in Objective C. I make use of "@objc(alias_name)".

    Here is the code, Let's have a swift protocol with @objc attribute and alias name to use in the ObjC code.

    @objc(ObjTableViewReloadable) protocol TableViewReloadable: class {
       func reloadRow(at index: IndexPath)
       func reloadSection(at index: Int)
       func reloadTable()
    }
    

    Now lets farword declare our protocol in .h file

    @protocol ObjTableViewReloadable;
    

    You can now conform to this protocol in .m file and add required methods implementation.

    #import "MyApp-Swift.h"
    @interface MyObjcViewController () 
    

提交回复
热议问题