我有一个Objective-C初始化程序(来自另一个项目),我发现它很有用。现在我想把它移植到Swift,并且Swift的命名约定存在问题。
·H
@interface UIViewController (FromNib)
-(nullable instancetype)initFromNib;
@end
的.m
#import "FromNib.h"
@implementation UIViewController (FromNib)
-(nullable instancetype)initFromNib {
self = [self initWithNibName: NSStringFromClass([self class])
bundle: [NSBundle mainBundle]];
if (self == nil) {
NSLog(@"\nNib with name %@ not found in the main bundle.\n", NSStringFromClass([self class]));
}
return self;
}
@end
由于Objective-C识别名称以init
开头的方法,因此它将init
视为与initWith...
或initFrom
不同。
Swift基于传递的参数进行区分。我认为使init()
与初始化程序不同的唯一方法是传递一个伪参数:
extension UIViewController {
convenience init(FromNib:Int) {
self.init()
// the rest of the code
}
}
在Swift中编写无参数初始化是否有不同的方法,并避免与指定的init()
混淆?
答案 0 :(得分:0)
@Sulthan和@Martin R
好点。默认init()
就是这样做的。谢谢。问题解决了。