Prerequisite environment:
Not limited to Swift, "avoiding reassignment to variables (as much as possible)" is widely understood as a theory for writing secure code.
Related Links: Why do you want to avoid reassigning to variables
However, in practice, it is easy to think that you have to write the reassignment code in the case where there is a branch in the assignment of the initial value as shown below.
Sample A
//The variable foo is ""hoge" or "fuga"The intention is that one of them will be initialized and will not change after that. "
var foo = ""
if isHoge {
foo = "hoge"
} else {
foo = "fuga"
}
The above code does not prevent reassignment to the variable foo
.
It remains possible that foo
will be set to a value other than ("hoge" or "fuga") somewhere.
The above code can be improved as follows.
Sample B
let foo: String
if isHoge {
foo = "hoge"
} else {
foo = "fuga"
}
** If there is a path that is not initialized, the compiler will make an error **, so if you intend to "set the initial value and then do not reassign it",
--Variable initialization omission can be prevented. --It can be guaranteed that the value does not change after initialization.
In that respect, I think the code in sample B is safer.
Recommended Posts