Rodrigo Ramos
Rodrigo Ramos

Reputation: 337

What must be accomplished in the implementation of an initializer?

What must be accomplished in the implementation of an initializer?

a. All properties need to be initialized with a value

b. All properties need to be explicitly assigned a value.

c. All non-Optional properties need to be initialized.
   Sorry, that's incorrect. 
   Optionals need to be initialized as well.

d. The object needs to be created

What answer is correct and why?

Upvotes: 2

Views: 106

Answers (1)

luk2302
luk2302

Reputation: 57114

In my opinion that is very confusingly stated question. Because what you as the developer have to do is Option c.

Take a look at this simple code example and the minimum init to be compilable

class SomeClass {
    var a : AnyObject
    var b : AnyObject?
    var c : AnyObject!
    var d = ":)"

    init() {
        a = ""
        print("initialized")
    }
}

The swift docu states

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition. These actions are described in the following sections.

Option d. is imho non-sense since the object creation is handled by the underlying runtime environment and not via the initializer.

Now b. and a. remain with the tiny difference in wording explicitly assigned vs. initialized. I would therefore discard Option b because the b and c variable do not need any explicit value, the implicit nil is perfectly fine for the time (reading c will not work yet though)

Therefore my answer choice would be Option a. After the init method all properties need to have some specific value. Some of them explicitly in the init function, some of them implicitly.

tl;dr:

my final answer is Option a.

Upvotes: 2

Related Questions