"Initialize" Class Method for Classes in Swift

initialize class method for classes in Swift?

If you have an Objective-C class, it's easiest to just override +initialize. However, make sure subclasses of your class also override +initialize or else your class's +initialize may get called more than once! If you want, you can use dispatch_once() (mentioned below) to safeguard against multiple calls.

class MyView : UIView {
override class func initialize () {
// Do stuff
}
}

 

If you have a Swift class, the best you can get is dispatch_once() inside the init() statement.

private var once = dispatch_once_t()

class MyObject {
init () {
dispatch_once(&once) {
// Do stuff
}
}
}

This solution differs from +initialize (which is called the first time an Objective-C class is messaged) and thus isn't a true answer to the question. But it works good enough, IMO.

Swift Class Initialization Confusion

Answering your question directly: the initialization method is not necessary.

The variable randomizedSale is static, so you don't need an instance to use it. It has nothing to do with the initialization.

Since all your variables and functions are static you don't need to write an init method. If create something like:

class A { 
var x: Int
}

You will get an error because your variable x is not optional and you didn't provide any value for it so you have to write an init OR set an initial value.

class A { 
var x: Int // Write init or set a value here

init() {
x = 0
}
}

I strongly recommend you to read the section about initialization in Apple Docs.

Preferred way to initialize a class in Swift

“If a property always takes the same initial value, provide a default value rather than setting a value within an initializer. The end result is the same, but the default value ties the property’s initialization more closely to its declaration. It makes for shorter, clearer initializers and enables you to infer the type of the property from its default value. The default value also makes it easier for you to take advantage of default initializers and initializer inheritance, as described later in this chapter.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

Swift 3.1 deprecates initialize(). How can I achieve the same thing?

Easy/Simple Solution

A common app entry point is an application delegate's applicationDidFinishLaunching. We could simply add a static function to each class that we want to notify on initialization, and call it from here.

This first solution is simple and easy to understand. For most cases, this is what I'd recommend. Although the next solution provides results that are more similar to the original initialize() function, it also results in slightly longer app start up times. I no longer think
it is worth the effort, performance degradation, or code complexity in most cases. Simple code is good code.

Read on for another option. You may have reason to need it (or perhaps parts of it).


Not So Simple Solution

The first solution doesn't necessarily scale so well. And what if you are building a framework, where you'd like your code to run without anyone needing to call it from the application delegate?

Step One

Define the following Swift code. The purpose is to provide a simple entry point for any class that you would like to imbue with behavior akin to initialize() - this can now be done simply by conforming to SelfAware. It also provides a single function to run this behavior for every conforming class.

protocol SelfAware: class {
static func awake()
}

class NothingToSeeHere {

static func harmlessFunction() {

let typeCount = Int(objc_getClassList(nil, 0))
let types = UnsafeMutablePointer<AnyClass>.allocate(capacity: typeCount)
let autoreleasingTypes = AutoreleasingUnsafeMutablePointer<AnyClass>(types)
objc_getClassList(autoreleasingTypes, Int32(typeCount))
for index in 0 ..< typeCount { (types[index] as? SelfAware.Type)?.awake() }
types.deallocate(capacity: typeCount)

}

}

Step Two

That's all good and well, but we still need a way to actually run the function we defined, i.e. NothingToSeeHere.harmlessFunction(), on application startup. Previously, this answer suggested using the Objective-C code to do this. However, it seems that we can do what we need using only Swift. For macOS or other platforms where UIApplication is not available, a variation of the following will be needed.

extension UIApplication {

private static let runOnce: Void = {
NothingToSeeHere.harmlessFunction()
}()

override open var next: UIResponder? {
// Called before applicationDidFinishLaunching
UIApplication.runOnce
return super.next
}

}

Step Three

We now have an entry point at application startup, and a way to hook into this from classes of your choice. All that is left to do: instead of implementing initialize(), conform to SelfAware and implement the defined method, awake().

Initializer in a Swift Class

If your object can be "re-initialized" then just initialize it to some base-state by default:

class Test {
var thing: String = "" // Add default value
init() {
reinit()
}

func reinit() {
self.thing = "Hello"
}
}

As a rule, I think this is probably a bad design. Instead of "reinitializing," replace this class with a struct, and just throw it away and replace it when you want to reset things. As a rule, structs are very cheap to create. But if you need this, then default values is ok.

Initialize a class in Swift

private let myViewController = MyViewController()
means myViewController have instance of MyViewController class whenever it will be used in class.

But private let myViewController: MyViewController! in that case we must assign the instance of MyViewController to myViewController before using myViewController otherwise there will be a crash.

swift - Initializing another class inside a class?

change this line:

var pet = Pets(petName: String, noise: String, canMakeNoise: Bool)

to this line:

var pet: Pets?

And after that you can create an instance of your Human class such as:

var human = Human(humanName: "chris", petName: "abc", noise: "hi", canMakeNoise: true)
var dog = Pets(petName: "erty", noise:"bark", canMakeNoise:true)
human.pet = dog

Swift - Initializing class variables which are classes

First every class name Start with capitalize character. So change your node_ class like this

class Node
{
var label: String
var coordinates: position_
init()
{
name = ""
coordinates = position_()
}
}

Also change your class position_ with Position.
Instead of using _ try to write class name in capitalize first character of each word like this PositionMarker.

Hope this will help you.



Related Topics



Leave a reply



Submit