6

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

1
  • I went through the same issue. Rather than using a dummy parameter you can change your static method name. For example : + (instancetype)sharedInstance; goes through the bridge. Commented Apr 3, 2015 at 13:16

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Calling ApplicationAssembly() went straight through to init, which was actually private, because the class method did some further config before returning. . . luckily that extra config could be safely moved to init. . . Not sure what to do if a) Not an ObjC class that I control or b) It couldn't be moved.
@JasperBlues Ya I'm not sure either. I did some experimentation and I couldn't find an initializer that would call the class method
Side note: new is probably best left for [MyClass new] which is shorthand to [[MyClass alloc] init].
it is not the best choice to use a keyword (like new) as name of any ivar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.