从Objective-C工厂方法创建Swift实例 [英] Create Swift instance from Objective-C factory method

查看:76
本文介绍了从Objective-C工厂方法创建Swift实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有TyphoonAssembly的子类,其中包含以下工厂方法:

I have a sub-class of TyphoonAssembly, which contains this factory method:

+ (instancetype)assembly;

我正尝试在测试中使用它,如下所示:

I'm trying to use it in a test as follows:

var assembly : ApplicationAssembly! = ApplicationAssembly.assembly()

但是出现错误"assembly()不可用"(参见图片).

But get the error 'assembly() is unavailable' (see image).

从Objective-C类方法创建Swift实例的正确方法是什么?

What's the correct way to create a Swift instance from an objective-C class method.

推荐答案

当从Objective-C桥接代码以快速进行编译时,编译器会尝试将类方法的构造函数转换为普通的初始化程序.尝试仅调用ApplicationAssembly()并查看它是否调用了您的类方法.您还可以更改类方法的名称,以使编译器不会将其识别为常见的构造函数命名.

When bridging code from objective-C to swift the compiler tries to convert class method constructors to normal initializers. Try calling just ApplicationAssembly() and see if it calls your class method. You can also change the name of your class method so that the compiler does not recognize it as a common constructor naming.

以下是一个功能良好的网桥示例:

Here is an example of a functioning bridge:

// Objective-C
@implementation ApplicationAssembly

+ (instancetype)assemblyWithValue:(NSString *)value
{
    ApplicationAssembly *new = [[self alloc] init];
    new.value = @"Some_Value_To_Make_Sure_That_This_Code_Is_Running";
    return new;
}

@end

// Swift
var assembly = ApplicationAssembly(value: "")
println(assembly.value) // outputs "Some_Value_To_Make_Sure_That_This_Code_Is_Running"

它不能与空类方法构造函数一起使用,就像您要访问的那样.

It doesn't work with an empty class method constructor like you are trying to access.

这篇关于从Objective-C工厂方法创建Swift实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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