不能在Objective-C中使用Swift类

时间:2022-09-07 09:25: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 here. But my problem is that Xcode haven't created the -Swift.h file, only the bridging headers. So I created it, but it's actually empty. I can use all my ObjC classes in Swift, but I can't do it vice versa. I marked my swift class with @objc but it didn't help. What can I do now?

我尝试在我的app中集成Swift代码,我的app是用Objective-C编写的,我增加了一个Swift类。我已经完成了这里描述的一切。但我的问题是Xcode没有创建-Swift。h文件,只有桥接头。我创建了它,但它实际上是空的。我可以在Swift中使用所有ObjC类,但我不能反过来使用。我用@objc标记了我的swift类,但没有用。我现在能做什么?

EDIT: Apple says:" When you import Swift code into Objective-C, you rely on an Xcode-generated header file to expose those files to Objective-C. [...] The name of this header is your product module name followed by adding “-Swift.h”. "

编辑:苹果说:“当你将Swift代码导入Objective-C时,你需要依赖一个xcode生成的头文件来将这些文件公开给Objective-C。[…这个标题的名称是您的产品模块名称,后面加上“-Swift.h”。”

Now when I want to import that File, it gives an error:

现在当我想导入那个文件时,它会出现一个错误:

    //MainMenu.m

    #import "myProjectModule-Swift.h" //Error: 'myProjectModule-Swift.h' file not found

    @implementation MainMenu

Here is my FBManager.swift file:

这是我的FBManager。快速文件:

@objc class FBManager: NSObject {

    var descr = "FBManager class"

    init() {
        super.init()
    }

    func desc(){
        println(descr)
    }

    func getSharedGameState() -> GameState{
        return GameState.sharedGameState() //OK! GameState is written in Objective-C and no error here
    }
}

19 个解决方案

#1


452  

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 :-)

我花了大约4个小时尝试在基于Xcode Objective-C的项目中启用Swift。我的“myproject-Swift。h"文件被成功创建,但是我的Xcode没有看到我的swift类。因此,我决定创建一个新的基于Xcode object的项目,最后我找到了正确的答案!希望这篇文章能帮助别人:-)

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

  1. Create new *.swift file (in Xcode) or add it by using Finder
  2. 创建新*。swift文件(在Xcode中)或使用Finder添加
  3. Create an Objective-C bridging header when Xcode ask you about that
  4. 当Xcode询问您的时候,创建一个Objective-C桥接头。
  5. Implement your Swift class with @objc attribute:

    使用@objc属性实现Swift类:

    import UIKit
    
    @objc public class CustomView: UIView {
        override func draw(_ rect: CGRect) {
            // Drawing code
        }
    }
    
  6. Open Build Settings and check those parameters:

    打开构建设置并检查这些参数:

    • Defines Module : YES
    • 定义模块:是的
    • 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

      这个头由Xcode自动生成

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

    在您的*中导入Swift接口头。m文件

    #import "myproject-Swift.h"
    

    Don't pay attention to errors and warnings.

    不要注意错误和警告。

  8. Clean and rebuild your Xcode project
  9. 清理并重新构建您的Xcode项目
  10. Profit!
  11. 利润!

#2


56  

Don't create the header file yourself. Delete the one you created.

不要自己创建头文件。删除您创建的。

Make sure your Swift classes are tagged with @objc or inherit from a class that derives (directly or indirectly) from NSObject.

确保您的Swift类被标记为@objc,或者继承自NSObject派生的类(直接或间接)。

Xcode won't generate the file if you have any compiler errors in your project - make sure your project builds cleanly.

如果您的项目中有任何编译错误,Xcode将不会生成该文件——请确保您的项目构建干净。

#3


30  

Allow Xcode to do its work, do not add/create Swift header manually. Just add @objc before your Swift class ex.

允许Xcode做它的工作,不要手动添加/创建Swift报头。在您的Swift类ex之前添加@objc即可。

@objc class YourSwiftClassName: UIViewController

In your project setting search for below flags and change it to YES (Both Project and Target)

在您的项目设置搜索下面的旗帜,并改变它是的(包括项目和目标)

Defines Module : YES
Always Embed Swift Standard Libraries : YES
Install Objective-C Compatibility Header : YES

Then clean the project and build once, after build succeed (it should probably) import below header file in your objective-c class .m file

然后在构建成功之后(可能应该)在objective-c类.m文件中导入下面的头文件,然后清理项目并构建一次。

#import "YourProjectName-Swift.h" 

Boooom!

Boooom !

#4


23  

Also probably helpful for those of you with a Framework target:

可能对你们中有框架目标的人也有帮助:

The import statement of the auto-generated header file looks a bit different from app targets. In addition to the other things mentioned in other answers use

自动生成的头文件的导入语句看起来有点不同于应用程序目标。除了在其他答案中提到的其他事情之外,使用

#import <ProductName/ProductModuleName-Swift.h>

instead of

而不是

#import "ProductModuleName-Swift.h"

as per Apples documentation on Mix & Match for framework targets.

根据苹果公司的文件,混合和匹配框架目标。

#5


14  

Make sure your project defines a module and you have given a name to the module. Then rebuild, and Xcode will create the -Swift.h header file and you will be able to import.

确保您的项目定义了一个模块,并且您已经为这个模块命名。然后重新构建,Xcode将创建-Swift。h头文件,你可以导入。

You can set module definition and module name in your project settings.

您可以在项目设置中设置模块定义和模块名。

#6


11  

I had the same issue and it turned out special symbols in the module name are replaced by xcode (in my case dashes ended up being underscores). In project settings check "module name" to find the module name for your project. After that either use ModuleName-Swift.h or rename the module in settings.

我遇到了同样的问题,结果发现模块名中的特殊符号被xcode替换(在我的例子中,破折号最后变成了下划线)。在项目设置中,勾选“模块名”以查找项目的模块名。之后要么使用模块化- swift。h或在设置中重命名模块。

#7


9  

The file is created automatically (talking about Xcode 6.3.2 here). But you won't see it, since it's in your Derived Data folder. After marking your swift class with @objc, compile, then search for Swift.h in your Derived Data folder. You should find the Swift header there.

该文件是自动创建的(在这里讨论Xcode 6.3.2)。但是您不会看到它,因为它在派生数据文件夹中。在使用@objc标记swift类之后,编译,然后搜索swift。h在派生数据文件夹中。你应该在那里找到Swift的报头。

I had the problem, that Xcode renamed my my-Project-Swift.h to my_Project-Swift.h Xcode doesn't like "." "-" etc. symbols. With the method above you can find the filename and import it to a Objective-C class.

我有个问题,Xcode把我的my- project - swift重命名了。my_Project-Swift h。h Xcode不喜欢"“-”等符号。通过上面的方法,您可以找到文件名并将其导入到Objective-C类中。

#8


8  

Just include #import "myProject-Swift.h" in .m or .h file

只包括# myProject-Swift进口”。h"在。m或。h文件中

P.S You will not find "myProject-Swift.h" in file inspector it's hidden. But it is generated by app automatically.

P。你找不到“myProject-Swift”。在文件检查器中它是隐藏的。但它是由app自动生成的。

#9


8  

Details: Objective-C project with Swift 3 code in Xcode 8.1

详细信息:在Xcode 8.1中使用Swift 3代码的Objective-C项目

Tasks:

任务:

  1. Use swift enum in objective-c class
  2. 在objective-c类中使用swift enum
  3. Use objective-c enum in swift class
  4. 在swift类中使用objective-c enum

FULL SAMPLE

1. Objective-C class which use Swift enum

ObjcClass.h

ObjcClass.h

#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, ObjcEnum) {
    ObjcEnumValue1,
    ObjcEnumValue2,
    ObjcEnumValue3
};

@interface ObjcClass : NSObject

+ (void) PrintEnumValues;

@end

ObjcClass.m

ObjcClass.m

#import "ObjcClass.h"
#import "SwiftCode.h"

@implementation ObjcClass

+ (void) PrintEnumValues {
    [self PrintEnumValue:SwiftEnumValue1];
    [self PrintEnumValue:SwiftEnumValue2];
    [self PrintEnumValue:SwiftEnumValue3];
}

+ (void) PrintEnumValue:(SwiftEnum) value {
    switch (value) {
        case SwiftEnumValue1:
            NSLog(@"-- SwiftEnum: SwiftEnumValue1");
            break;

        case SwiftEnumValue2:
        case SwiftEnumValue3:
            NSLog(@"-- SwiftEnum: long value = %ld", (long)value);
            break;
    }
}

@end

Detect Swift code in Objective-C code

In my sample I use SwiftCode.h to detect Swift code in Objective-C. This file generate automatically (I did not create a physical copy of this header file in a project), and you can only set name of this file:

在我的示例中,我使用SwiftCode。h检测Objective-C中的Swift码。这个文件自动生成(我没有在项目中创建这个头文件的物理副本),您只能设置这个文件的名称:

不能在Objective-C中使用Swift类

不能在Objective-C中使用Swift类

If the compiler can not find your header file Swift code, try to compile the project.

如果编译器找不到您的头文件Swift代码,请尝试编译项目。

2. Swift class which use Objective-C enum

import Foundation

@objc
enum SwiftEnum: Int {
    case Value1, Value2, Value3
}

@objc
class SwiftClass: NSObject {

    class func PrintEnumValues() {
        PrintEnumValue(.Value1)
        PrintEnumValue(.Value2)
        PrintEnumValue(.Value3)
    }

    class func PrintEnumValue(value: ObjcEnum) {
        switch value {
        case .Value1, .Value2:
            NSLog("-- ObjcEnum: int value = \(value.rawValue)")

        case .Value3:
            NSLog("-- ObjcEnum: Value3")
            break
        }

    }
}

Detect Objective-C code in Swift code

You need to create bridging header file. When you add Swift file in Objective-C project, or Objective-C file in swift project Xcode will suggest you to create bridging header.

您需要创建桥接头文件。当您在Objective-C项目中添加Swift文件,或在Swift项目Xcode中添加Objective-C文件时,将建议您创建桥接头。

不能在Objective-C中使用Swift类

You can change bridging header file name here:

您可以在这里更改桥接头文件名:

不能在Objective-C中使用Swift类

Bridging-Header.h

Bridging-Header.h

#import "ObjcClass.h"

Usage

#import "SwiftCode.h"
...
[ObjcClass PrintEnumValues];
[SwiftClass PrintEnumValues];
[SwiftClass PrintEnumValue:ObjcEnumValue3];

Result

不能在Objective-C中使用Swift类


MORE SAMPLES

Full integration steps Objective-c and Swift described above. Now I will write some other code examples.

Objective-c和Swift上面描述的完整集成步骤。现在我将编写一些其他的代码示例。

3. Call Swift class from Objective-c code

Swift class

斯威夫特类

import Foundation

@objc
class SwiftClass:NSObject {

    private var _stringValue: String
    var stringValue: String {
        get {
            print("SwiftClass get stringValue")
            return _stringValue
        }
        set {
            print("SwiftClass set stringValue = \(newValue)")
            _stringValue = newValue
        }
    }

    init (stringValue: String) {
        print("SwiftClass init(String)")
        _stringValue = stringValue
    }

    func printValue() {
        print("SwiftClass printValue()")
        print("stringValue = \(_stringValue)")
    }

}

Objective-C code (calling code)

objective - c代码(调用代码)

SwiftClass *obj = [[SwiftClass alloc] initWithStringValue: @"Hello World!"];
[obj printValue];
NSString * str = obj.stringValue;
obj.stringValue = @"HeLLo wOrLd!!!";

Result

结果

不能在Objective-C中使用Swift类

4. Call Objective-c class from Swift code

Objective-C class (ObjcClass.h)

objective - c类(ObjcClass.h)

#import <Foundation/Foundation.h>

@interface ObjcClass : NSObject
@property NSString* stringValue;
- (instancetype) initWithStringValue:(NSString*)stringValue;
- (void) printValue;
@end

ObjcClass.m

ObjcClass.m

#import "ObjcClass.h"

@interface ObjcClass()

@property NSString* strValue;

@end

@implementation ObjcClass

- (instancetype) initWithStringValue:(NSString*)stringValue {
    NSLog(@"ObjcClass initWithStringValue");
    _strValue = stringValue;
    return self;
}

- (void) printValue {
    NSLog(@"ObjcClass printValue");
    NSLog(@"stringValue = %@", _strValue);
}

- (NSString*) stringValue {
    NSLog(@"ObjcClass get stringValue");
    return _strValue;
}

- (void) setStringValue:(NSString*)newValue {
    NSLog(@"ObjcClass set stringValue = %@", newValue);
    _strValue = newValue;
}

@end

Swift code (calling code)

斯威夫特代码(调用代码)

if let obj = ObjcClass(stringValue:  "Hello World!") {
    obj.printValue()
    let str = obj.stringValue;
    obj.stringValue = "HeLLo wOrLd!!!";
}

Result

结果

不能在Objective-C中使用Swift类

5. Use Swift extension in Objective-c code

Swift extension

迅速扩展

extension UIView {
    static func swiftExtensionFunc() {
        NSLog("UIView swiftExtensionFunc")
    }
}

Objective-C code (calling code)

objective - c代码(调用代码)

[UIView swiftExtensionFunc];

6. Use Objective-c extension in swift code

Objective-C extension (UIViewExtension.h)

objective - c扩展(UIViewExtension.h)

#import <UIKit/UIKit.h>

@interface UIView (ObjcAdditions)
+ (void)objcExtensionFunc;
@end

UIViewExtension.m

UIViewExtension.m

@implementation UIView (ObjcAdditions)
+ (void)objcExtensionFunc {
    NSLog(@"UIView objcExtensionFunc");
}
@end

Swift code (calling code)

斯威夫特代码(调用代码)

UIView.objcExtensionFunc()

#10


5  

There is two condition,

有两个条件,

  • Use your swift file in objective c file.
  • 在目标c文件中使用您的swift文件。
  • Use your objective c file in swift file.
  • 在swift文件中使用目标c文件。

So, For that purpose, you have to follow this steps:

因此,为了达到这个目的,你必须遵循以下步骤:

  • Add your swift file in an objective-c project or vice-versa.
  • 在objective-c项目中添加swift文件,反之亦然。
  • Create header(.h) file.
  • 创建头文件(. h)。
  • Go to Build Settings and perform below steps with search,

    去建立设置和执行以下步骤搜索,

    1. search for this text "brid" and set a path of your header file.
    2. 搜索此文本“brid”并设置头文件的路径。
    3. "Defines Module": YES.
    4. “定义模块”:是的。
    5. "Always Embed Swift Standard Libraries" : YES.
    6. “始终嵌入Swift标准库”:是的。
    7. "Install Objective-C Compatibility Header" : YES.
    8. “安装Objective-C兼容头”:是的。

After that, clean and rebuild your project.

之后,清理并重新构建项目。

Use your swift file in objective c file.

In that case,First write "@objc" before your class in swift file.

在这种情况下,首先在您的类之前在swift文件中写入“@objc”。

After that ,In your objective c file, write this,

然后,在目标c文件中,写这个,

  #import "YourProjectName-Swift.h"

Use your objective c file in swift file.

In that case, In your header file, write this,

在这种情况下,在你的头文件中,

  #import "YourObjective-c_FileName.h"

I hope this will help you.

我希望这对你有帮助。

#11


4  

@sig answer is one of the best, however, it did not work for me with the old project (not new!), I needed some modifications. After a lot of variations I found the recipe for me (using XCode 7.2):

@sig的答案是最好的,但是,它并没有为我的旧项目工作(不是新的!),我需要一些修改。经过很多变化之后,我找到了我的食谱(使用XCode 7.2):

  1. Product Module Name : $(PRODUCT_NAME:c99extidentifier)
  2. 产品模块名:$(PRODUCT_NAME:c99extidentifier)
  3. Defines Module : NO
  4. 定义模块:不
  5. Embedded Content Contains Swift : NO
  6. 嵌入式内容包含Swift: NO
  7. Install Objective-C Compatibility Header : YES
  8. 安装Objective-C兼容性头:是的。
  9. Objective-C Bridging Header : ProjectName-Bridging-Header.h
  10. Objective-C桥接头:ProjectName-Bridging-Header.h

The last point (5) was crucial. I put it only on the second section (Targets field), the Project field should be left empty: 不能在Objective-C中使用Swift类 Otherwise, it did not generate the right "Project-Swift.h" file for me (it did not include swift methods).

最后一点(5)至关重要。我只把它放在第二部分(target字段),项目字段应该为空:否则,它不会生成正确的“Project- swift”。h“文件(不包含swift方法)。

#12


3  

In my case, apart from these steps:

在我的例子中,除了这些步骤:

  1. Product Module Name : myproject
  2. 产品模块名称:myproject。
  3. Defines Module : YES
  4. 定义模块:是的
  5. Embedded Content Contains Swift : YES
  6. 嵌入式内容包含Swift:是的
  7. Install Objective-C Compatibility Header : YES
  8. 安装Objective-C兼容性头:是的。
  9. Objective-C Bridging Header : $(SRCROOT)/Sources/SwiftBridging.h
  10. Objective-C桥接头:$(SRCROOT)/ source / swiftbridge .h

I have needed to put the class as public in order to create productName-Swift.h file:

我需要将类设置为public,以便创建product - swift。h文件:

import UIKit

   @objc public class TestSwift: NSObject {
       func sayHello() {
          print("Hi there!")
       }
   }

#13


2  

I just discovered that adding a directory of swift files to a project won't work. You need to create a group first for the directory, then add the swift files...

我刚刚发现在项目中添加swift文件目录是行不通的。您需要首先为目录创建一个组,然后添加swift文件……

#14


2  

I had the same problem and finally it appeared that they weren't attached to the same targets. The ObjC class is attached to Target1 and Target2, the Swift class is only attached to the Target1 and is not visible inside the ObjC class.

我遇到了同样的问题,最后,他们似乎没有把目标放在同一个目标上。ObjC类附加到Target1和Target2, Swift类只附加到Target1,在ObjC类中不可见。

Hope this helps someone.

希望这可以帮助别人。

#15


0  

I have the same error: myProjectModule-Swift.h file not found", but, in my case, real reason was in wrong deployment target: "Swift is unavailable on OS X earlier than 10.9; please set MACOSX_DEPLOYMENT_TARGET to 10.9 or later (currently it is '10.7')" so, when I've changed deployment target to 10.9 - project had been compiled successfully.

我有同样的错误:myProjectModule-Swift。h文件未找到”,但是,在我的例子中,真正的原因是部署目标错误:“Swift在OS X上在10.9之前不可用;请将MACOSX_DEPLOYMENT_TARGET设置为10.9或更高版本(目前是‘10.7’)”,因此,当我将部署目标更改为10.9时——项目已经成功编译。

#16


0  

My issue was that the auto-generation of the -swift.h file was not able to understand a subclass of CustomDebugStringConvertible. I changed class to be a subclass of NSObject instead. After that, the -swift.h file now included the class properly.

我的问题是-swift的自动生成。h文件不能理解CustomDebugStringConvertible的子类。我将类改为NSObject的子类。在那之后,迅速。h文件现在正确地包含了类。

#17


0  

my problem was I got stuck after xcode created the bridge file but still I got error in header file name MYPROJECTNAME-swift.h

我的问题是在xcode创建网桥文件后我被卡住了,但是我在头文件名称MYPROJECTNAME-swift.h中还是有错误

1.I check in terminal and search for all auto created swift bridge files:

1。我登录终端,搜索所有自动创建的swift网桥文件:

find ~/library/Developer/Xcode/DerivedData/ -name "*-Swift.h"|xargs basename|sort -

寻找~ /图书馆/开发/ Xcode / DerivedData / *斯威夫特- name”。h”| xargs basename | -

you see what xcode created.

您将看到xcode创建了什么。

  1. in my case, I had space in my project name and xcode replace this is '_'
  2. 在我的例子中,我的项目名中有空格xcode替换为_

#18


0  

I had issues in that I would add classes to my objective-c bridging header, and in those objective-c headers that were imported, they were trying to import the swift header. It didn't like that.

我有一些问题,我要在objective-c桥接头中添加类,在那些导入的objective-c头中,他们试图导入swift头。它不喜欢。

So in all my objective-c classes that use swift, but are also bridged, the key was to make sure that you use forward class declarations in the headers, then import the "*-Swift.h" file in the .m file.

因此,在我所有使用swift的objective-c类中,但它们也是桥接的,关键是确保在header中使用forward类声明,然后导入“*-Swift”。h"文件在。m文件中。

#19


0  

I didnt have to change any settings in the build or add @obj to the class.

我不需要更改构建中的任何设置或向类添加@obj。

All I had to do was to create bridge-header which was automatically created when I created Swift classes into Objective-c project. And then I just had to do

我所要做的就是创建bridge-header,这是我在Objective-c项目中创建Swift类时自动创建的。然后我就必须这么做

import "Bedtime-Swift.h" <- inside objective-c file that needed to use that swift file.

#1


452  

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 :-)

我花了大约4个小时尝试在基于Xcode Objective-C的项目中启用Swift。我的“myproject-Swift。h"文件被成功创建,但是我的Xcode没有看到我的swift类。因此,我决定创建一个新的基于Xcode object的项目,最后我找到了正确的答案!希望这篇文章能帮助别人:-)

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

  1. Create new *.swift file (in Xcode) or add it by using Finder
  2. 创建新*。swift文件(在Xcode中)或使用Finder添加
  3. Create an Objective-C bridging header when Xcode ask you about that
  4. 当Xcode询问您的时候,创建一个Objective-C桥接头。
  5. Implement your Swift class with @objc attribute:

    使用@objc属性实现Swift类:

    import UIKit
    
    @objc public class CustomView: UIView {
        override func draw(_ rect: CGRect) {
            // Drawing code
        }
    }
    
  6. Open Build Settings and check those parameters:

    打开构建设置并检查这些参数:

    • Defines Module : YES
    • 定义模块:是的
    • 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

      这个头由Xcode自动生成

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

    在您的*中导入Swift接口头。m文件

    #import "myproject-Swift.h"
    

    Don't pay attention to errors and warnings.

    不要注意错误和警告。

  8. Clean and rebuild your Xcode project
  9. 清理并重新构建您的Xcode项目
  10. Profit!
  11. 利润!

#2


56  

Don't create the header file yourself. Delete the one you created.

不要自己创建头文件。删除您创建的。

Make sure your Swift classes are tagged with @objc or inherit from a class that derives (directly or indirectly) from NSObject.

确保您的Swift类被标记为@objc,或者继承自NSObject派生的类(直接或间接)。

Xcode won't generate the file if you have any compiler errors in your project - make sure your project builds cleanly.

如果您的项目中有任何编译错误,Xcode将不会生成该文件——请确保您的项目构建干净。

#3


30  

Allow Xcode to do its work, do not add/create Swift header manually. Just add @objc before your Swift class ex.

允许Xcode做它的工作,不要手动添加/创建Swift报头。在您的Swift类ex之前添加@objc即可。

@objc class YourSwiftClassName: UIViewController

In your project setting search for below flags and change it to YES (Both Project and Target)

在您的项目设置搜索下面的旗帜,并改变它是的(包括项目和目标)

Defines Module : YES
Always Embed Swift Standard Libraries : YES
Install Objective-C Compatibility Header : YES

Then clean the project and build once, after build succeed (it should probably) import below header file in your objective-c class .m file

然后在构建成功之后(可能应该)在objective-c类.m文件中导入下面的头文件,然后清理项目并构建一次。

#import "YourProjectName-Swift.h" 

Boooom!

Boooom !

#4


23  

Also probably helpful for those of you with a Framework target:

可能对你们中有框架目标的人也有帮助:

The import statement of the auto-generated header file looks a bit different from app targets. In addition to the other things mentioned in other answers use

自动生成的头文件的导入语句看起来有点不同于应用程序目标。除了在其他答案中提到的其他事情之外,使用

#import <ProductName/ProductModuleName-Swift.h>

instead of

而不是

#import "ProductModuleName-Swift.h"

as per Apples documentation on Mix & Match for framework targets.

根据苹果公司的文件,混合和匹配框架目标。

#5


14  

Make sure your project defines a module and you have given a name to the module. Then rebuild, and Xcode will create the -Swift.h header file and you will be able to import.

确保您的项目定义了一个模块,并且您已经为这个模块命名。然后重新构建,Xcode将创建-Swift。h头文件,你可以导入。

You can set module definition and module name in your project settings.

您可以在项目设置中设置模块定义和模块名。

#6


11  

I had the same issue and it turned out special symbols in the module name are replaced by xcode (in my case dashes ended up being underscores). In project settings check "module name" to find the module name for your project. After that either use ModuleName-Swift.h or rename the module in settings.

我遇到了同样的问题,结果发现模块名中的特殊符号被xcode替换(在我的例子中,破折号最后变成了下划线)。在项目设置中,勾选“模块名”以查找项目的模块名。之后要么使用模块化- swift。h或在设置中重命名模块。

#7


9  

The file is created automatically (talking about Xcode 6.3.2 here). But you won't see it, since it's in your Derived Data folder. After marking your swift class with @objc, compile, then search for Swift.h in your Derived Data folder. You should find the Swift header there.

该文件是自动创建的(在这里讨论Xcode 6.3.2)。但是您不会看到它,因为它在派生数据文件夹中。在使用@objc标记swift类之后,编译,然后搜索swift。h在派生数据文件夹中。你应该在那里找到Swift的报头。

I had the problem, that Xcode renamed my my-Project-Swift.h to my_Project-Swift.h Xcode doesn't like "." "-" etc. symbols. With the method above you can find the filename and import it to a Objective-C class.

我有个问题,Xcode把我的my- project - swift重命名了。my_Project-Swift h。h Xcode不喜欢"“-”等符号。通过上面的方法,您可以找到文件名并将其导入到Objective-C类中。

#8


8  

Just include #import "myProject-Swift.h" in .m or .h file

只包括# myProject-Swift进口”。h"在。m或。h文件中

P.S You will not find "myProject-Swift.h" in file inspector it's hidden. But it is generated by app automatically.

P。你找不到“myProject-Swift”。在文件检查器中它是隐藏的。但它是由app自动生成的。

#9


8  

Details: Objective-C project with Swift 3 code in Xcode 8.1

详细信息:在Xcode 8.1中使用Swift 3代码的Objective-C项目

Tasks:

任务:

  1. Use swift enum in objective-c class
  2. 在objective-c类中使用swift enum
  3. Use objective-c enum in swift class
  4. 在swift类中使用objective-c enum

FULL SAMPLE

1. Objective-C class which use Swift enum

ObjcClass.h

ObjcClass.h

#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, ObjcEnum) {
    ObjcEnumValue1,
    ObjcEnumValue2,
    ObjcEnumValue3
};

@interface ObjcClass : NSObject

+ (void) PrintEnumValues;

@end

ObjcClass.m

ObjcClass.m

#import "ObjcClass.h"
#import "SwiftCode.h"

@implementation ObjcClass

+ (void) PrintEnumValues {
    [self PrintEnumValue:SwiftEnumValue1];
    [self PrintEnumValue:SwiftEnumValue2];
    [self PrintEnumValue:SwiftEnumValue3];
}

+ (void) PrintEnumValue:(SwiftEnum) value {
    switch (value) {
        case SwiftEnumValue1:
            NSLog(@"-- SwiftEnum: SwiftEnumValue1");
            break;

        case SwiftEnumValue2:
        case SwiftEnumValue3:
            NSLog(@"-- SwiftEnum: long value = %ld", (long)value);
            break;
    }
}

@end

Detect Swift code in Objective-C code

In my sample I use SwiftCode.h to detect Swift code in Objective-C. This file generate automatically (I did not create a physical copy of this header file in a project), and you can only set name of this file:

在我的示例中,我使用SwiftCode。h检测Objective-C中的Swift码。这个文件自动生成(我没有在项目中创建这个头文件的物理副本),您只能设置这个文件的名称:

不能在Objective-C中使用Swift类

不能在Objective-C中使用Swift类

If the compiler can not find your header file Swift code, try to compile the project.

如果编译器找不到您的头文件Swift代码,请尝试编译项目。

2. Swift class which use Objective-C enum

import Foundation

@objc
enum SwiftEnum: Int {
    case Value1, Value2, Value3
}

@objc
class SwiftClass: NSObject {

    class func PrintEnumValues() {
        PrintEnumValue(.Value1)
        PrintEnumValue(.Value2)
        PrintEnumValue(.Value3)
    }

    class func PrintEnumValue(value: ObjcEnum) {
        switch value {
        case .Value1, .Value2:
            NSLog("-- ObjcEnum: int value = \(value.rawValue)")

        case .Value3:
            NSLog("-- ObjcEnum: Value3")
            break
        }

    }
}

Detect Objective-C code in Swift code

You need to create bridging header file. When you add Swift file in Objective-C project, or Objective-C file in swift project Xcode will suggest you to create bridging header.

您需要创建桥接头文件。当您在Objective-C项目中添加Swift文件,或在Swift项目Xcode中添加Objective-C文件时,将建议您创建桥接头。

不能在Objective-C中使用Swift类

You can change bridging header file name here:

您可以在这里更改桥接头文件名:

不能在Objective-C中使用Swift类

Bridging-Header.h

Bridging-Header.h

#import "ObjcClass.h"

Usage

#import "SwiftCode.h"
...
[ObjcClass PrintEnumValues];
[SwiftClass PrintEnumValues];
[SwiftClass PrintEnumValue:ObjcEnumValue3];

Result

不能在Objective-C中使用Swift类


MORE SAMPLES

Full integration steps Objective-c and Swift described above. Now I will write some other code examples.

Objective-c和Swift上面描述的完整集成步骤。现在我将编写一些其他的代码示例。

3. Call Swift class from Objective-c code

Swift class

斯威夫特类

import Foundation

@objc
class SwiftClass:NSObject {

    private var _stringValue: String
    var stringValue: String {
        get {
            print("SwiftClass get stringValue")
            return _stringValue
        }
        set {
            print("SwiftClass set stringValue = \(newValue)")
            _stringValue = newValue
        }
    }

    init (stringValue: String) {
        print("SwiftClass init(String)")
        _stringValue = stringValue
    }

    func printValue() {
        print("SwiftClass printValue()")
        print("stringValue = \(_stringValue)")
    }

}

Objective-C code (calling code)

objective - c代码(调用代码)

SwiftClass *obj = [[SwiftClass alloc] initWithStringValue: @"Hello World!"];
[obj printValue];
NSString * str = obj.stringValue;
obj.stringValue = @"HeLLo wOrLd!!!";

Result

结果

不能在Objective-C中使用Swift类

4. Call Objective-c class from Swift code

Objective-C class (ObjcClass.h)

objective - c类(ObjcClass.h)

#import <Foundation/Foundation.h>

@interface ObjcClass : NSObject
@property NSString* stringValue;
- (instancetype) initWithStringValue:(NSString*)stringValue;
- (void) printValue;
@end

ObjcClass.m

ObjcClass.m

#import "ObjcClass.h"

@interface ObjcClass()

@property NSString* strValue;

@end

@implementation ObjcClass

- (instancetype) initWithStringValue:(NSString*)stringValue {
    NSLog(@"ObjcClass initWithStringValue");
    _strValue = stringValue;
    return self;
}

- (void) printValue {
    NSLog(@"ObjcClass printValue");
    NSLog(@"stringValue = %@", _strValue);
}

- (NSString*) stringValue {
    NSLog(@"ObjcClass get stringValue");
    return _strValue;
}

- (void) setStringValue:(NSString*)newValue {
    NSLog(@"ObjcClass set stringValue = %@", newValue);
    _strValue = newValue;
}

@end

Swift code (calling code)

斯威夫特代码(调用代码)

if let obj = ObjcClass(stringValue:  "Hello World!") {
    obj.printValue()
    let str = obj.stringValue;
    obj.stringValue = "HeLLo wOrLd!!!";
}

Result

结果

不能在Objective-C中使用Swift类

5. Use Swift extension in Objective-c code

Swift extension

迅速扩展

extension UIView {
    static func swiftExtensionFunc() {
        NSLog("UIView swiftExtensionFunc")
    }
}

Objective-C code (calling code)

objective - c代码(调用代码)

[UIView swiftExtensionFunc];

6. Use Objective-c extension in swift code

Objective-C extension (UIViewExtension.h)

objective - c扩展(UIViewExtension.h)

#import <UIKit/UIKit.h>

@interface UIView (ObjcAdditions)
+ (void)objcExtensionFunc;
@end

UIViewExtension.m

UIViewExtension.m

@implementation UIView (ObjcAdditions)
+ (void)objcExtensionFunc {
    NSLog(@"UIView objcExtensionFunc");
}
@end

Swift code (calling code)

斯威夫特代码(调用代码)

UIView.objcExtensionFunc()

#10


5  

There is two condition,

有两个条件,

  • Use your swift file in objective c file.
  • 在目标c文件中使用您的swift文件。
  • Use your objective c file in swift file.
  • 在swift文件中使用目标c文件。

So, For that purpose, you have to follow this steps:

因此,为了达到这个目的,你必须遵循以下步骤:

  • Add your swift file in an objective-c project or vice-versa.
  • 在objective-c项目中添加swift文件,反之亦然。
  • Create header(.h) file.
  • 创建头文件(. h)。
  • Go to Build Settings and perform below steps with search,

    去建立设置和执行以下步骤搜索,

    1. search for this text "brid" and set a path of your header file.
    2. 搜索此文本“brid”并设置头文件的路径。
    3. "Defines Module": YES.
    4. “定义模块”:是的。
    5. "Always Embed Swift Standard Libraries" : YES.
    6. “始终嵌入Swift标准库”:是的。
    7. "Install Objective-C Compatibility Header" : YES.
    8. “安装Objective-C兼容头”:是的。

After that, clean and rebuild your project.

之后,清理并重新构建项目。

Use your swift file in objective c file.

In that case,First write "@objc" before your class in swift file.

在这种情况下,首先在您的类之前在swift文件中写入“@objc”。

After that ,In your objective c file, write this,

然后,在目标c文件中,写这个,

  #import "YourProjectName-Swift.h"

Use your objective c file in swift file.

In that case, In your header file, write this,

在这种情况下,在你的头文件中,

  #import "YourObjective-c_FileName.h"

I hope this will help you.

我希望这对你有帮助。

#11


4  

@sig answer is one of the best, however, it did not work for me with the old project (not new!), I needed some modifications. After a lot of variations I found the recipe for me (using XCode 7.2):

@sig的答案是最好的,但是,它并没有为我的旧项目工作(不是新的!),我需要一些修改。经过很多变化之后,我找到了我的食谱(使用XCode 7.2):

  1. Product Module Name : $(PRODUCT_NAME:c99extidentifier)
  2. 产品模块名:$(PRODUCT_NAME:c99extidentifier)
  3. Defines Module : NO
  4. 定义模块:不
  5. Embedded Content Contains Swift : NO
  6. 嵌入式内容包含Swift: NO
  7. Install Objective-C Compatibility Header : YES
  8. 安装Objective-C兼容性头:是的。
  9. Objective-C Bridging Header : ProjectName-Bridging-Header.h
  10. Objective-C桥接头:ProjectName-Bridging-Header.h

The last point (5) was crucial. I put it only on the second section (Targets field), the Project field should be left empty: 不能在Objective-C中使用Swift类 Otherwise, it did not generate the right "Project-Swift.h" file for me (it did not include swift methods).

最后一点(5)至关重要。我只把它放在第二部分(target字段),项目字段应该为空:否则,它不会生成正确的“Project- swift”。h“文件(不包含swift方法)。

#12


3  

In my case, apart from these steps:

在我的例子中,除了这些步骤:

  1. Product Module Name : myproject
  2. 产品模块名称:myproject。
  3. Defines Module : YES
  4. 定义模块:是的
  5. Embedded Content Contains Swift : YES
  6. 嵌入式内容包含Swift:是的
  7. Install Objective-C Compatibility Header : YES
  8. 安装Objective-C兼容性头:是的。
  9. Objective-C Bridging Header : $(SRCROOT)/Sources/SwiftBridging.h
  10. Objective-C桥接头:$(SRCROOT)/ source / swiftbridge .h

I have needed to put the class as public in order to create productName-Swift.h file:

我需要将类设置为public,以便创建product - swift。h文件:

import UIKit

   @objc public class TestSwift: NSObject {
       func sayHello() {
          print("Hi there!")
       }
   }

#13


2  

I just discovered that adding a directory of swift files to a project won't work. You need to create a group first for the directory, then add the swift files...

我刚刚发现在项目中添加swift文件目录是行不通的。您需要首先为目录创建一个组,然后添加swift文件……

#14


2  

I had the same problem and finally it appeared that they weren't attached to the same targets. The ObjC class is attached to Target1 and Target2, the Swift class is only attached to the Target1 and is not visible inside the ObjC class.

我遇到了同样的问题,最后,他们似乎没有把目标放在同一个目标上。ObjC类附加到Target1和Target2, Swift类只附加到Target1,在ObjC类中不可见。

Hope this helps someone.

希望这可以帮助别人。

#15


0  

I have the same error: myProjectModule-Swift.h file not found", but, in my case, real reason was in wrong deployment target: "Swift is unavailable on OS X earlier than 10.9; please set MACOSX_DEPLOYMENT_TARGET to 10.9 or later (currently it is '10.7')" so, when I've changed deployment target to 10.9 - project had been compiled successfully.

我有同样的错误:myProjectModule-Swift。h文件未找到”,但是,在我的例子中,真正的原因是部署目标错误:“Swift在OS X上在10.9之前不可用;请将MACOSX_DEPLOYMENT_TARGET设置为10.9或更高版本(目前是‘10.7’)”,因此,当我将部署目标更改为10.9时——项目已经成功编译。

#16


0  

My issue was that the auto-generation of the -swift.h file was not able to understand a subclass of CustomDebugStringConvertible. I changed class to be a subclass of NSObject instead. After that, the -swift.h file now included the class properly.

我的问题是-swift的自动生成。h文件不能理解CustomDebugStringConvertible的子类。我将类改为NSObject的子类。在那之后,迅速。h文件现在正确地包含了类。

#17


0  

my problem was I got stuck after xcode created the bridge file but still I got error in header file name MYPROJECTNAME-swift.h

我的问题是在xcode创建网桥文件后我被卡住了,但是我在头文件名称MYPROJECTNAME-swift.h中还是有错误

1.I check in terminal and search for all auto created swift bridge files:

1。我登录终端,搜索所有自动创建的swift网桥文件:

find ~/library/Developer/Xcode/DerivedData/ -name "*-Swift.h"|xargs basename|sort -

寻找~ /图书馆/开发/ Xcode / DerivedData / *斯威夫特- name”。h”| xargs basename | -

you see what xcode created.

您将看到xcode创建了什么。

  1. in my case, I had space in my project name and xcode replace this is '_'
  2. 在我的例子中,我的项目名中有空格xcode替换为_

#18


0  

I had issues in that I would add classes to my objective-c bridging header, and in those objective-c headers that were imported, they were trying to import the swift header. It didn't like that.

我有一些问题,我要在objective-c桥接头中添加类,在那些导入的objective-c头中,他们试图导入swift头。它不喜欢。

So in all my objective-c classes that use swift, but are also bridged, the key was to make sure that you use forward class declarations in the headers, then import the "*-Swift.h" file in the .m file.

因此,在我所有使用swift的objective-c类中,但它们也是桥接的,关键是确保在header中使用forward类声明,然后导入“*-Swift”。h"文件在。m文件中。

#19


0  

I didnt have to change any settings in the build or add @obj to the class.

我不需要更改构建中的任何设置或向类添加@obj。

All I had to do was to create bridge-header which was automatically created when I created Swift classes into Objective-c project. And then I just had to do

我所要做的就是创建bridge-header,这是我在Objective-c项目中创建Swift类时自动创建的。然后我就必须这么做

import "Bedtime-Swift.h" <- inside objective-c file that needed to use that swift file.