How can I import Swift code to Objective-C?

前端 未结 15 2348
南方客
南方客 2020-11-22 02:52

I have written a library in Swift and I wasn\'t able to import it to my current project, written in Objective-C.

Are there any ways to import it?

#i         


        
相关标签:
15条回答
  • 2020-11-22 03:30

    Checkout the pre-release notes about Swift and Objective C in the same project

    https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_75

    You should be importing

    #import "SCLAlertView-Swift.h"
    
    0 讨论(0)
  • 2020-11-22 03:33

    Instructions from the Apple website:

    To import Swift code into Objective-C from the same framework

    Under Build Settings, in Packaging, make sure the Defines Module setting for that framework target is set to Yes. Import the Swift code from that framework target into any Objective-C .m file within that framework target using this syntax and substituting the appropriate names:

    #import "ProductName-Swift.h"

    Revision:

    You can only import "ProductName-Swift.h" in .m files.

    The Swift files in your target will be visible in Objective-C .m files containing this import statement.

    To avoid cyclical references, don’t import Swift into an Objective-C header file. Instead, you can forward declare a Swift class to use it in an Objective-C header. Note that you cannot subclass a Swift class in Objective-C.

    enter image description here

    0 讨论(0)
  • 2020-11-22 03:34

    You need to import ProductName-Swift.h. Note that it's the product name - the other answers make the mistake of using the class name.

    This single file is an autogenerated header that defines Objective-C interfaces for all Swift classes in your project that are either annotated with @objc or inherit from NSObject.

    Considerations:

    • If your product name contains spaces, replace them with underscores (e.g. My Project becomes My_Project-Swift.h)

    • If your target is a framework, you need to import <ProductName/ProductName-Swift.h>

    • Make sure your Swift file is member of the target

    0 讨论(0)
提交回复
热议问题