SLN SLN - 6 months ago 9
Swift Question

Why optional constant does not automatically have a default value of nil

The following code works fine

struct carConfi {
var owner: String?
let brand: String = "BMW"
var currentMile: Double = 2000
}

let tomCar = carConfi()


However, if I change the type of the property
owner
to constant, there will be an error at the initializer

struct carConfi {
let owner: String? // Change to constant
let brand: String = "BMW"
var currentMile: Double = 2000
}

let tomCar = carConfi() //error: missing argument for parameter 'owner' in call


I did a bit search, it turns out that it is because the optional variables automatically have a default value of nil

I guess: Because once the constant is set, it then cannot be changed, if the optional constant automatically received an
nil
then it will keep as an unchangeable
nil
that's very silly and may against the users will

Question: My college doesn't fully convinced by the guess, he told me there must be more reasons for that. I would very appreciate if someone can explain that to me

Thx

Answer

Not setting a read-only (constant) field with either an initialization expression or an initializer is almost certainly an indication of an error in your program.

Since you have no other opportunity to set the value of your let field, the value of the field is going to remain nil (or some other default). It is rather unlikely that a programmer would find such behavior desirable, and request it on purpose.

That is why Swift marks this situation as an error. On the other hand, if you actually wanted your String constant to remain nil, you could add an expression to set it to nil, and silence the error:

let owner: String? = nil // Pretty useless, but allowed
Comments