更新时间:2022-12-04 10:54:27
我花了大约 4 个小时试图在我的基于 Xcode
Objective-C 的项目中启用 Swift
.我的 myproject-Swift.h
文件已成功创建,但我的 Xcode
没有看到我的 Swift-classes
.所以,我决定创建一个新的 Xcode
基于 Objc 的项目,最后,我找到了正确的答案!希望这篇文章能帮助别人:-)
*.swift
文件(在 Xcode 中)或使用 Finder 添加它.Objective-C 桥接头
.实现你的 Swift 类:
导入基础//必要时使用@objc 或@objcMembers 注释类 Foo {//..}
打开构建设置并检查这些参数:
YES
复制&在搜索栏中粘贴参数名称
myproject
确保您的产品模块名称不包含任何特殊字符
YES
将 *.swift
文件添加到项目后,此属性将出现在构建设置中
myproject-Swift.h
此标头由 Xcode 自动生成
$(SRCROOT)/myproject-Bridging-Header.h
在 *.m 文件中导入 Swift 接口标头.
#import "myproject-Swift.h"
不要关注错误和警告.
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?
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". "
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:
@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
}
}
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 :-)
*.swift
file (in Xcode) or add it by using Finder.Objective-C bridging header
when Xcode asks you about that.Implement your Swift class:
import Foundation
// use @objc or @objcMembers annotation if necessary
class Foo {
//..
}
Open Build Settings and check these parameters:
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
Import Swift interface header in your *.m file.
#import "myproject-Swift.h"
Don't pay attention to errors and warnings.