Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 702
squarefrog Avatar asked Apr 12 '16 10:04

squarefrog


2 Answers

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

 @objc public init(url: URL) { 
   //your code 
 }
like image 147
iOS Lifee Avatar answered Oct 14 '22 06:10

iOS Lifee


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
like image 10
Lasse Avatar answered Oct 14 '22 06:10

Lasse