Savan Kavaiya
Savan Kavaiya

Reputation: 43

Object initialization in swift

What would be a good practice for object initialization in swift from given below? And why?

1. Initialize while declaring

class MyClass {
    var object: MyObject = MyObject()
}

2. Initialize in init()

class MyClass {

    var object: MyObject

    init() {
        object = MyObject()
    }
}

If there are any other approaches then feel free to give suggestions.

Upvotes: 0

Views: 4035

Answers (1)

David Pasztor
David Pasztor

Reputation: 54795

In this simple case, it's better to assign a value to object right at declaration, there's no need to do it in the initializer of MyClass.

So you can simply do:

class MyClass {
    let object = MyObject()
}

However, there might be more complicated scenarios, such as when MyObject itself has an initializer with input parameters, which only become known at the initialization of MyClass when you can't initialize object at declaration, so you need to do it in the initializer of MyClass.

class MyObject {
    let prop: String

    init(_ prop:String){
        self.prop = prop
    }
}

class MyClass {
    let object: MyObject

    init(objectProp:String){
        self.object = MyObject(objectProp)
    }
}

Upvotes: 5

Related Questions