Can a var type be changed into let type or vice versa in swift. I try to search it online but there is no such content available online.
Asked
Active
Viewed 614 times
0
-
2[duplicate](https://stackoverflow.com/questions/24002092/what-is-the-difference-between-let-and-var-in-swift) – Vadim Nikolaev Jan 16 '20 at 10:31
-
The question does not make any sense, to be honest. – Sulthan Jan 16 '20 at 10:52
2 Answers
1
You cannot change the mutability of a variable once it has been declared. However, you can create a mutable/immutable copy of any variable.
let immutable = 21
var mutableCopy = immutable
mutableCopy = 2
var mutable = 3
let immutableCopy = 4
You also have to be aware though that mutability and copying means different things for reference and value types.

Dávid Pásztor
- 51,403
- 9
- 85
- 116
0
conversion from let
to var
let a = "" /* Constant */
var b = a /* Variable */
b = "b"
conversion from var
to let
var c = "" /* Variable */
let d = c /* Constant */
Declaring Constants and Variables Constants and variables must be declared before they’re used. You declare constants with the let keyword and variables with the var keyword. source
Struct (Value Type) vs Class (Reference Type)
class TotoClass {
var str = "str"
}
struct TotoStruct {
var str = "str"
}
let classToto = TotoClass()
let structToto = TotoStruct()
classToto.str = "new Str"
structToto.str = "new Str"
last line doesn't compile and there will be an error
Cannot assign to property: 'structToto' is a 'let' constant

Blazej SLEBODA
- 8,936
- 7
- 53
- 93