我尝试在我的应用程序中集成 Swift
代码。我的应用程序是用 Objective-C
编写的,我添加了一个 Swift
类。我已经完成了所有描述here .但我的问题是 Xcode
没有创建 -Swift.h
文件,只有桥接头。所以我创建了它,但它实际上是空的。
我可以在 Swift 中使用我所有的 ObjC 类,但反之则不行。我用 @objc
标记了我的 swift 类,但它没有帮助。我现在能做什么?
编辑:Apple 说:“当您将 Swift 代码导入到 Objective-C 时,您依赖于 Xcode-generated
头文件将这些文件公开给 Objective-C。[...]此 header 的名称是您的产品模块名称,后跟“-Swift.h”。“
现在当我想导入那个文件时,它给出了一个错误:
//MainMenu.m
#import "myProjectModule-Swift.h" //Error: 'myProjectModule-Swift.h' file not found
@implementation MainMenu
这是我的 FBManager.swift 文件:
@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
}
}
最佳答案
我花了大约 4 个小时尝试在我的基于 Xcode
Objective-C 的项目中启用 Swift
。我的 myproject-Swift.h
文件已成功创建,但我的 Xcode
没有看到我的 Swift-classes
。所以,我决定创建一个新的基于 Xcode
Objc 的项目,最后,我找到了正确的答案!希望这篇文章对某人有所帮助:-)
*.swift
文件(在 Xcode 中)或使用 Finder 添加它。Objective-C 桥接头
。实现你的 Swift 类:
import Foundation
// use @objc or @objcMembers annotation if necessary
class Foo {
//..
}
打开build设置并检查这些参数:
YES
Copy & Paste parameter name in a search bar
myproject
Make sure that your Product Module Name doesn't contain any special characters
YES
Once you've added
*.swift
file to the project this property will appear in Build Settings
myproject-Swift.h
This header is auto-generated by Xcode
$(SRCROOT)/myproject-Bridging-Header.h
在您的 *.m 文件中导入 Swift 接口(interface) header 。
#import "myproject-Swift.h"
Don't pay attention to errors and warnings.
https://stackoverflow.com/questions/24206732/