Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 385 Vote(s) - 3.52 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Subclassing NSObject in Swift - Best Practice with Initializers

#1
Here is the layout of an example Class, can someone guide me on what's best practice when creating a subclass of 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?

Should my more **specific** (the one that takes a string) initializer simply call `self.init()` at the end rather than `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 ?

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:

[To see links please register here]

Reply

#2
I'm not Swift ninja but I would write `MyClass` as:

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][1]


[1]:

[To see links please register here]

Reply

#3
In complement to the answers, a good idea is to call super.init() *before* other statements. I think it's a stronger requirement in Swift because allocations are implicit.
Reply

#4
If someProperty can be nil, then I think you want to define the property as:

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.
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through