【问题标题】:How can I use method of an ObjC class which contains a forward declare Swift class in Swift?如何在 Swift 中使用包含前向声明 Swift 类的 ObjC 类的方法?
【发布时间】:2015-11-18 09:16:40
【问题描述】:
//CoolSwiftClass.swift
@objc(MyCoolSwiftClass)
class CoolSwiftClass: NSObject {}

//MyObjCViewController.h
@class MyCoolSwiftClass;
@interface MyObjCViewController : UIViewController
- (instancetype)initWithMyCoolSwiftClass:(MyCoolSwiftClass *)myCoolSwiftClassInstance;
@end

//SadSwiftClass.swift
class SadSwiftClass: UIViewController {
  override func loadView() {
    super.loadView()
    //This won't work
    let myObjCViewController = MyObjCViewController(coolSwiftClass: coolSwiftClassInstance)
  }
}

似乎 Swift 可以找到前向声明 MyCoolSwiftClass,但它找不到它实际上是 CoolSwiftClass

我在Swift and Objective-C in the Same Project 中没有找到任何可以帮助我的东西。

2015-11-19 13:34 CST 更新

只需将 repo 上传到 GitHub:SO33775908

2015-11-19 13:47 CST 更新

找出解决方法:

没有特殊的 ObjC 名称。结账分行No special ObjC name

2015-11-19 14:47 CST 更新

另一种产生警告的解决方法:

@compatibility_alias with several warnings

【问题讨论】:

  • And I didn't find anything that can help me in Swift and Objective-C in the Same Project. – 你是认真的吗?有一整节关于将 Swift 导入到 Objective-C 中,并且在第一段中说明了您的问题的解决方案......
  • @akashivskyy 是的,我尝试了一些看似有帮助但失败的解决方案。
  • 那么让我引用具体部分-When you import Swift code into Objective-C, you rely on an Xcode-generated header file to expose those files to Objective-C. This automatically generated file is an Objective-C header that declares the Swift interfaces in your target. It can be thought of as an umbrella header for your Swift code. The name of this header is your product module name followed by adding "-Swift.h".
  • @akashivskyy 看来你不明白我在问什么。我有那个伞头。我可能会上传一个 repo 来证明。
  • 那么请澄清:)

标签: objective-c swift forward-declaration


【解决方案1】:

我发现的最好方法是解决方法 1:

没有特殊的 ObjC 名称

如果你已经使用了一段时间的特殊 ObjC 名称,你可以使用这样的名称:

//ClassName_Alias.h
#define MyCoolSwiftClass CoolSwiftClass

//CoolSwiftClass.swift
@objc
class CoolSwiftClass: NSObject {}

请查看问题更新 1 以获取示例存储库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    相关资源
    最近更新 更多