ios 在 Swift 中子类化 NSObject - 初始化器的最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25343330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Subclassing NSObject in Swift - Best Practice with Initializers
提问by Woodstock
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
? - and how should I call the super init ?
子类化时在 Swift 中设置初始值设定项的正确方法是什么NSObject
?- 我应该如何调用 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,你总是调用它并简单地在更具体的 init 中设置属性:Objective-C Multiple Initialisers
回答by Maxim Shoustin
I'm not Swift ninja but I would write MyClass
as:
我不是 Swift 忍者,但我会这样写MyClass
:
class MyClass: NSObject {
var someProperty: NSString // no need (!). It will be initialised from controller
init(fromString string: NSString) {
self.someProperty = string
super.init()
}
convenience override init() {
self.init(fromString:"John") // calls above mentioned controller with default name
}
}
回答by Jed Lau
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.
这也消除了对自定义初始化程序的需要(至少对于此属性),因为该属性在初始化时不需要值。
回答by tontonCD
In complement to the answers, a good idea is to call super.init() beforeother statements. I think it's a stronger requirement in Swift because allocations are implicit.
作为对答案的补充,一个好主意是在其他语句之前调用 super.init() 。我认为在 Swift 中这是一个更强的要求,因为分配是隐式的。