Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Swift instance from Objective-C factory method

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()

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

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

enter image description here

like image 303
Jasper Blues Avatar asked Jun 07 '14 04:06

Jasper Blues


1 Answers

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.

like image 92
drewag Avatar answered Nov 17 '22 22:11

drewag