Can't use Swift classes inside Objective-C

前端 未结 25 2570
野趣味
野趣味 2020-11-22 08:10

I try to integrate Swift code in my app.My app is written in Objective-C and I added a Swift class. I\'ve done everything described he

25条回答
  •  半阙折子戏
    2020-11-22 08:15

    I spent about 4 hours trying to enable Swift in my Xcode Objective-C based project. My myproject-Swift.h file was created successfully, but my Xcode didn't see my Swift-classes. So, I decided to create a new Xcode Objc-based project and finally, I found the right answer! Hope this post will help someone :-)

    Step by step Swift integration for Xcode Objc-based project:

    1. Create new *.swift file (in Xcode) or add it by using Finder.
    2. Create an Objective-C bridging header when Xcode asks you about that.
    3. Implement your Swift class:

      import Foundation
      
      // use @objc or @objcMembers annotation if necessary
      class Foo {
          //..
      }
      
    4. Open Build Settings and check these parameters:

      • Defines Module : YES

        Copy & Paste parameter name in a search bar

      • Product Module Name : myproject

        Make sure that your Product Module Name doesn't contain any special characters

      • Install Objective-C Compatibility Header : YES

        Once you've added *.swift file to the project this property will appear in Build Settings

      • Objective-C Generated Interface Header : myproject-Swift.h

        This header is auto-generated by Xcode

      • Objective-C Bridging Header : $(SRCROOT)/myproject-Bridging-Header.h
    5. Import Swift interface header in your *.m file.

      #import "myproject-Swift.h"
      

      Don't pay attention to errors and warnings.

    6. Clean and rebuild your Xcode project.
    7. Profit!

提交回复
热议问题