[英]Is it possible to call Swift convenience initializer in Objective-C
假設我在Swift中有一個方便的初始化程序:
extension UIImage {
convenience init?(bundleNamed name: String) {
let bundle = NSBundle(forClass: Foo.self)
self.init(named: name, inBundle: bundle, compatibleWithTraitCollection: nil)
}
}
我怎么能在Objective-C中調用它? 以下不起作用:
[UIImage bundleNamed:@"Bar"];
[[UIImage alloc] initWithBundleNamed:@"Bar"];
我是否只需要為Objective-C提供額外的類擴展?
解決方案 :按照Lasse的回答,我必須做的步驟是:
在Objective-C類實現文件中,添加
#import <ModuleName-Swift.h>
然后我不得不刪除派生數據並重建。 然后我能夠使用便利初始化程序如下:
[[UIImage alloc] initWithBundleNamed: @"Bar"];
我不需要將初始化程序聲明為public
因為internal
的默認級別對於我的模塊來說已經足夠了。
查看使用Swift與Cocoa和Objective-C(Swift 2.2) - 混合和匹配 。 它似乎歸結為
public
你的便利初始化,和 [YourProductModuleName]-Swift.h
導入到您的代碼中 請注意! 如果您使用Objective-C中沒有的任何Swift功能(如可選值),則在Objective-C中無法訪問它。 所以解決它們。
public convenience init(title:String?, message:String?) {
self.init()
self.title = title
self.message = message
}
以上代碼無法訪問,因此在這種情況下刪除可選項將有所幫助。
是的我們可以使用它注意:@objc和公眾很重要
@objc public init(url: URL) {
//your code
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.