简体   繁体   English

在 Swift 中子类化 NSObject - 初始化器的最佳实践

[英]Subclassing NSObject in Swift - Best Practice with Initializers

Here is the layout of an example Class, can someone guide me on what's best practice when creating a subclass of NSObject?这是示例类的布局,有人可以指导我创建 NSObject 的子类时的最佳实践吗?

class MyClass: NSObject {

    var someProperty: NSString! = nil

    override init() {
        self.someProperty = "John"
        super.init()
    }

    init(fromString string: NSString) {
        self.someProperty = string
        super.init()
    }

}

Is this correct, am I following best practice here?这是正确的,我在这里遵循最佳实践吗?

I wonder if I'm correctly setting up the initializers (one that sets the string to a default, and one which I can pass in a string)?我想知道我是否正确设置了初始化程序(将字符串设置为默认值的初始化程序,以及可以传入字符串的初始化程序)?

Should I call super.init() at the end of each of the initializers?我应该在每个初始值设定项的末尾调用super.init()吗?

Should my more specific (the one that takes a string) initializer simply call self.init() at the end rather than super.init() ?我的更具体的(接受字符串的)初始值设定项是否应该在最后简单地调用self.init()而不是super.init()

What is the right way to set up the initializers in Swift when subclassing NSObject ?子类化NSObject时,在 Swift 中设置初始值设定项的正确方法是什么? - and how should I call the super init ? - 我应该如何调用 super init ?

This question (albeit in Objective C) suggests you should have an init, which you always call and simply set the properties in more specific inits: Objective-C Multiple Initialisers这个问题(尽管在 Objective C 中)建议你应该有一个 init,你总是调用它并简单地在更具体的初始化中设置属性: Objective-C Multiple Initialisers

I'm not Swift ninja but I would write MyClass as:我不是 Swift ninja,但我会将MyClass写为:

class MyClass: NSObject {
    
    var someProperty: NSString // no need (!). It will be initialised from controller 
    
    init(fromString string: NSString) {
        self.someProperty = string
        super.init() // can actually be omitted in this example because will happen automatically.
    }
    
    convenience override init() {
        self.init(fromString:"John") // calls above mentioned controller with default name
    }        
}

See the initialization section of the documentation请参阅文档初始化部分

If someProperty can be nil, then I think you want to define the property as:如果 someProperty 可以为零,那么我认为您想将该属性定义为:

var someProperty: NSString?

This also eliminates the need for a custom initializer (at least, for this property), since the property doesn't require a value at initialization time.这也消除了对自定义初始化程序的需要(至少对于此属性),因为该属性在初始化时不需要值。

In complement to the answers, a good idea is to call super.init() before other statements.作为对答案的补充,一个好主意是其他语句之前调用 super.init()。 I think it's a stronger requirement in Swift because allocations are implicit.我认为在 Swift 中这是一个更强的要求,因为分配是隐式的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM