将 Objective-C 无参数初始化重写为 Swift 便利初始化

Rewriting an Objective-C parameterless init to Swift convenience init

我有一个 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 开头的方法,因此它将 initinitWith...initFrom 区别开来。 Swift 根据传递的参数进行区分。使 init() 与我的初始值设定项不同的唯一方法(我想到的)是传递一个伪参数:

extension UIViewController {

    convenience init(FromNib:Int) {
        self.init()
        // the rest of the code
    }
}

有没有不同的方法在Swift中编写一个无参数的init,并避免它与指定的init()混淆?

@Sulthan 和@Martin R

说得好。默认 init() 正是这样做的。谢谢你。问题已解决。