简体   繁体   中英

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.

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM