squarefrog
squarefrog

Reputation: 4822

Is it possible to call Swift convenience initializer in Objective-C

Say I have a convenience initializer in Swift:

extension UIImage {
    convenience init?(bundleNamed name: String) {
        let bundle = NSBundle(forClass: Foo.self)
        self.init(named: name, inBundle: bundle, compatibleWithTraitCollection: nil)
    }
}

How might I call this in Objective-C? The following doesn't work:

[UIImage bundleNamed:@"Bar"];
[[UIImage alloc] initWithBundleNamed:@"Bar"];

Do I need an additional class extension solely for Objective-C?


Solution: following Lasse's answer below, the steps I had to do were:

In the Objective-C classes implementation file, add

#import <ModuleName-Swift.h>

then I had to delete derived data and rebuild. Then I was able to use the convenience initializer as follows:

[[UIImage alloc] initWithBundleNamed: @"Bar"];

I didn't need to declare the initializer as public because the default level of internal was sufficient for my module.

Upvotes: 11

Views: 5034

Answers (3)

iOS Lifee
iOS Lifee

Reputation: 2201

Yes we can use it Note: @objc and public are important

 @objc public init(url: URL) { 
   //your code 
 }

Upvotes: 3

Muhammad Waqas
Muhammad Waqas

Reputation: 900

Please note! If you are using any of Swift features that are not available in Objective-C (like Optional values), it would not be accessible in Objective-C. So fix them.

 public convenience init(title:String?, message:String?) {
    self.init()
    self.title = title
    self.message = message
}

Above code is not accessible, so removing optional will help in this case.

Upvotes: 2

Lasse
Lasse

Reputation: 650

Check out Using Swift with Cocoa and Objective-C (Swift 2.2) - Mix and Match. What it seems to come down to is

  1. Making your convenience initializer public, and
  2. Importing an XCode-generated header file [YourProductModuleName]-Swift.h into your code

Upvotes: 10

Related Questions