I would like to ask something about type-casting in Swift.
There are 2 classes.
RootViewController
MyViewController
and the class hierarchy is like below:
class RootViewController: UIViewController {
}
class MyViewController: RootViewController {
}
and, I want to simply call instance
function to create an instance from xib file.
so I implemented below function in RootViewController
.
Objective-C
+ (instancetype)instance {
return [[[self class] alloc] initWithNibName:NSStringFromClass([self class]) bundle:nil];
}
Swift
public class func instance<T:RootViewController>() -> T {
let type = self as UIViewController.Type
let name = NSStringFromClass(type).components(separatedBy: ".").last!
let instance = type.init(nibName: name, bundle: nil)
return instance as! T
}
and, usage is like below.
Objective-C
MyViewController *vc = [MyViewController instance];
Swift
let vc = MyViewController.instance() as! MyViewController
Question:
Do I have to always cast the type of instance using as! MyViewController
in Swift?
Or can anybody advise me a better approach in Swift?
Any help would be appreciated!