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
In Swift, if we define a variable to be an optional variable, in that case, this variable can have no value at all. If optional variable is assigned with nil , then this says that there is no value in this variable. To check if this variable is not nil, we can use Swift Inequality Operator !=
However there is another data type in Swift called Optional, whose default value is a null value ( nil ). You can use optional when you want a variable or constant contain no value in it. An optional type may contain a value or absent a value (a null value).
Question : What's the difference optional between nil and . None? Answer : There is no difference.
If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.
Not setting a read-only (constant) field with either an:
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
Constants are set once, and once only. If you wanted it to be null or 0, then you would set it. You always define a constant on initiation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With