Swift/ObjC循环导入 [英] Swift/ObjC circular import

查看:80
本文介绍了Swift/ObjC循环导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个主要是Objective-C但正在转换为Swift的现有大型代码库.

I am working on an existing large codebase that is predominately Objective-C but is in the process of converting to Swift.

新类正在Swift中实现,但是其中一些类需要从现有的ObjC代码中进行访问.为了遵循ObjC和Swift的最佳实践,新类没有前缀,但是为ObjC定义了前缀.

New classes are being implemented in Swift, but some of these classes need to be accessed from existing ObjC code. In an attempt to follow both ObjC and Swift best practices, the new classes do not have a prefix, but are defined with a prefix for ObjC.

/**
 Create contrived class that is named XXClassA in ObjC and ClassA in Swift.
 */
@objc(XXClassA) class ClassA: NSObject {
    let foo = "bar"
}

到目前为止,这一直很好. Swift代码使用ClassA(),而ObjC使用[[XXClassA alloc] init].删除所有引用XXClassA的ObjC代码后,也可以从Swift类中删除@objc(XXClassA).

So far this has been working great; Swift code uses ClassA() and ObjC uses [[XXClassA alloc] init]. Once all ObjC code that references XXClassA is removed, @objc(XXClassA) can also be removed from the Swift class.

不幸的是,如果您有一个ObjC类引用XXClassA,然后Swift代码尝试在ClassA内部使用该新类,则此操作将失败.

Unfortunately this breaks down if you have an ObjC class reference XXClassA and then the Swift code attempts to use that new class inside of ClassA.

说我创建了一个名为XXClassC的ObjC类,它使用XXClassA(实际上是Swift类ClassA)实例化了自己

Say I create an ObjC class, named XXClassC and it instantiates itself using an XXClassA (which is really the Swift class ClassA)

//
//  XXClassC.h
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@class XXClassA;

@interface XXClassC : NSObject

-(instancetype)initWithA:(XXClassA *)classA;

@end

NS_ASSUME_NONNULL_END

现在已建立循环引用.如果我尝试从ClassA内部使用XXClassC,则初始化程序不可用.

The circular reference is now in place. If I attempt to use XXClassC from inside of the ClassA, the initializer is not available.

如果我重新定义ClassA为这样,一切都会好起来的.

If I redefine ClassA as this instead, all is well again.

class XXClassA: NSObject {
    let foo = "bar"
}

我知道为什么会这样,并且已经有了解决方法,但是我想继续使用这种带前缀的ObjC类的模式.关于如何避免循环导入,但又保留命名约定的任何想法?

I understand why this is happening and the fix I have in place, however I want to continue to use this pattern of prefixed ObjC classes. Any ideas on how to avoid the circular import, but also keep the naming convention?

此处提供完整代码示例: https://gist.github.com/justAnotherDev/78483f9d94e40fd90c38

Full code sample here: https://gist.github.com/justAnotherDev/78483f9d94e40fd90c38

推荐答案

我遇到了同样的问题.我的解决方法是:

I'm having the same problem. My workaround is:

  • 为Swift类使用objc样式的前缀名称.
  • 添加类型别名:typealias ClassA = XXClassA.
  • 始终使用Swift代码中的未前缀名称.

使用这种模式,至少在最后一个objc依赖项消失后,就可以轻松删除前缀.

With this pattern it's at least easy to remove the prefix when the last objc dependency is gone.

这篇关于Swift/ObjC循环导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆