问题
I have an Objective-C category used to customise
UIStoryboard's '+ (UIStoryboard *)storyboardWithName:(NSString *)name'.
It is used to determine which storyboard file to call when dealing with multiple devices. Now I need to change it to Swift.
It seems that I need to create a "Swift Extension", but am having issues getting it to work.
Here is what I have:
extension UIStoryboard {
convenience init(name: String, storyboardBundleOrNil: NSBundle?)
{
var storyboard: UIStoryboard?
var storyboardName: String?
// Don't adjust name if it's universal storyboard (Xcode 6, iOS 8)
storyboardName = name;
if (name.rangeOfString("_Universal") == nil)
{
if (UIDevice.currentDevice().userInterfaceIdiom == .Pad)
{
storyboardName = storyboardName!+"_iPad"
}
else
{
storyboardName = storyboardName!+"_iPhone"
}
}
// storyboard = UIStoryboard(name: storyboardName!, storyboardBundleOrNil: storyboardBundleOrNil!)
assert(storyboard != nil, "Storyboard %@ not found!")
//return storyboard!;
self.init(name: storyboardName!, storyboardBundleOrNil: storyboardBundleOrNil!)
}
}
回答1:
You cannot override a Swift method in an extension. See the documentation on Extensions for reference.
You cannot use extensions to override existing methods or properties on Objective-C types.
You've also used the wrong signature. The correct signature is
init(name: String, bundle: NSBundle?)
It will allow you to create the convenience initializer, and it will use it when you call it in your own code, but the framework's implementation gets called from external code. It seems like a bug to me that it will allow you to declare an extension convenience initializer with the same name, as I can't find a way to call the original initializer, so you will just get infinite recursion the way you've written it.
来源:https://stackoverflow.com/questions/26664213/swift-how-to-override-an-init-function-was-a-category-in-objective-c