What is the difference between `let` and `var` in Swift?
Asked Answered
P

32

366

What is the difference between let and var in Apple's Swift language?

In my understanding, it is a compiled language but it does not check the type at compile time. It makes me confused. How does the compiler know about the type error? If the compiler doesn't check the type, isn't it a problem with production environment?

This error is given when I try to assign a value to a let:

Cannot assign to property: 'variableName' is a 'let' constant
Change 'let' to 'var' to make it mutable

Plagiarism answered 2/6, 2014 at 19:46 Comment(7)
let is for constants, var is for variables.Lamelliform
@Plagiarism What do you mean by no type checking at compile time? As far as I can tell, it's statically typed, but types are inferred if the compiler can figure it out by itself. But then I'm only on page 25... ;-)Katalin
This is on topic but a poorly phrased question. There are at least 2 questions (i) diff between let and var; (ii) type safe vs type infer. In addition, when the poster mentioned production stage, he really meant at run time.Faddish
Additionally, var used on variables that define collections (arrays & dictionary) creates a mutable collection (not just the reference but the content of the collection can be modified. The other usage of var is being able to modify params passed in a function: func foo(var bar:Int) will allow you to modify the param bar locally in the function scope.Supple
possible duplicate of Differentiate let and var in Swift Programming LanguageCathexis
@Khnle-Kevin for type Safety vs. type inference see hereVive
I feel like stackoverflow.com/questions/24002999/… is more helpful than any answers hereDesinence
S
445

The let keyword defines a constant:

let theAnswer = 42

The theAnswer cannot be changed afterwards. This is why anything weak can't be written using let. They need to change during runtime and you must be using var instead.

The var defines an ordinary variable.

What is interesting:

The value of a constant doesn’t need to be known at compile time, but you must assign the value exactly once.

Another strange feature:

You can use almost any character you like for constant and variable names, including Unicode characters:

let 🐶🐮 = "dogcow"

Excerpts From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=881256329


Community Wiki

Because comments are asking for adding other facts to the answer, converting this to community wiki answer. Feel free edit the answer to make it better.

Sunflower answered 2/6, 2014 at 19:46 Comment(17)
C and C++ allows Unicode identifiers as well, via UCNs. If the compiler supports any Unicode source encoding then you can just use the Unicode characters directly. For example auto 🐶🐮 = "dogcow"; works in C++ for clang.Fresno
@Fresno okay, i'm only not sure than i want debug a program like: if 😍 === 💝 { 💔 = ♠︎ } :) ;)Curvy
Does it apply to REPL? Because you can reassign the constant in REPL.Crumble
First, as noted above, this is totally different in the REPL. Second, if it's a constant it's not much of one. This works just fine in the compiler: let foo = [1,2,3]; foo[2] = 5; println("(foo)") // [1, 2, 5]Upshot
Why not just call it "const" instead of "let"?Torchbearer
@TylerCloutier it's not called let, it's just the way you say it, like in math (e.g. let x be 5, find y if xy=-10)Cowey
I believe const already exists in Objective C. I may be wrong but I think it is required to point to an object, unlike let where constants are not pointers.Unilobed
Does anybody except for the Chinese really care about the Unicode part? It's completely irrelevant to the question. jm said himself, unless you speak a language that uses Unicode characters, you shouldn't use them for variable names.Jasminjasmina
I am also more curious about the name "let". //also, I think unicode var names will make code review process more fun.Andaman
This answer, although the most upvoted, is missing any mention of how let/var behave when referring to objects instead of value types. The key is that in both cases you can still change the properties of the object, but cannot modify the pointer to refer to another object. This is not immediately obvious from basic examples involving integers and strings.Hideaway
@Hideaway Yes you are right. The main thing is missing here. Few people are saying that let is immutable and it can not be change later once initialised and I'm seeing that everyone is taking integers in their example. Try to take an NSMutableArray with let prefix and you can still add and remove objects from this. Correct is let makes a const pointer so we can not initialise the object again but we can change its value by adding or appending.Intoxicating
@Sunflower ??? I was just trying to make it more clear. You can see most of people are thinking that let can not be change. See other answer. And BTW I'm not pointing you anywhere.Intoxicating
@Intoxicating i do not need grind reputation (already 20k+) so, I converted the answer to "community-wiki answer". Now, feel free and edit the answer directly - and make it better. :)Curvy
@KevinFrost: Your comment is of course quite old, so I'm sure you already know this, but for posterity, let foo = [1, 2, 3]; foo[2] = 5; being legal was only a "feature" of the earliest version of the language. It was swiftly (ahem) fixed: How do you create an immutable array in Swift? (The first part of your comment, about the REPL, does stand.)Novellanovello
For clear distinction by example, please visit this useful page: youtube.com/watch?v=GfZwORo10TkAtrophy
Thanks for the explanation. Coming from Javascript where "let" is used for locally scoped variables it is making my head spin to use it in declaring constants.Horten
I wonder, is it a proper way of thinking: var lets you change the content stored in the STACK, while let does not allow you to change the content of the STACK. However, both var and let allow you to modify the HEAP. This is why let used with classes allows you to change object's properties, while let used with a struct does not allow you to change the properties of an instance of that struct. It all comes down to the fact that properties of a class's object are stored in a HEAP, while an instance of a struct is stored in the STACK.Almanac
U
36

According to The Swift Programming Language Book

Like C, Swift uses variables to store and refer to values by an identifying name. Swift also makes extensive use of variables whose values cannot be changed. These are known as constants, and are much more powerful than constants in C.

Both var and let are references, therefore let is a const reference. Using fundamental types doesn't really show how let is different than const. The difference comes when using it with class instances (reference types):

class CTest
{
    var str : String = ""
}

let letTest = CTest()
letTest.str = "test" // OK

letTest.str = "another test" // Still OK

//letTest = CTest() // Error

var varTest1 = CTest()
var varTest2 = CTest()
var varTest3 = CTest()

varTest1.str = "var 1"
varTest2.str = "var 2"
varTest3 = varTest1
varTest1.str = "var 3"

varTest3.str // "var 3"
Unequal answered 24/6, 2014 at 16:0 Comment(5)
This terminology is totally wrong... All references are indeed const references. There is no concept of a "const ref." Once bound, a reference is always bounded to the same memory address and can not be changed or "unseated." I believe you mean var is a "pointer" and let is a "const pointer"Autogenous
@Autogenous While what you are writing is correct in e.g. C++ I think the above snippet proves, that it's not the case in Swift. Pointers would allow pointer arithmetic and direct memory access, which again is not the case here. -- Edit: I've found no evidence that All references are indeed const references is true for every programming language.Unequal
BTW according to Wikipedia pointers are referencesUnequal
I agree your terminology is wrong. var and let have nothing to do with whether the identifier being bound is a to reference or not. If the type is a struct type, it is conceptually a value. If the type is a class it is conceptually a reference and the reference is a constant if let is used. If CTest was a struct, none of your letTest assignments would work.Abuttals
If the type is a struct it is a value type, there's nothing conceptual about it. The same with class - reference type. When modyfing a value type you create a new instance of this type. developer.apple.com/swift/blog/?id=10 So obviously you can't modify fields/properties of let bound to value type.Unequal
P
20

Swift let vs var

let - constant
var - variable

[Constant vs variable]
[Struct vs Class]

Official doc docs.swift.org says

The value of a constant can’t be changed once it’s set, whereas a variable can be set to a different value in the future.

This terminology actually describes a reassign mechanism

Mutability

Mutability - changeable - object's state can be changed after creation[About]

Value and Reference Type[About]

Reference Type(Class)

Swift's classes are mutable a-priory

var + class
It can be reassigned or changed

let + class = constant of address
It can not be reassigned and can be changed

Value(Struct, Enum)

Swift's struct can change their mutability status:

var + struct = mutable
It can be reassigned or changed

let + struct = *immutable or rather unmodifiable[About] [Example] [Example] = constant of value
It can not be reassigned or changed

*immutable - check testStructMutability test

Experiments:

class MyClass {
    var varClass: NSMutableString
    var varStruct: String
    
    let letClass: NSMutableString
    let letStruct: String
    
    init(_ c: NSMutableString, _ s: String) {
        varClass = c
        varStruct = s
        
        letClass = c
        letStruct = s
    }
}

struct MyStruct {
    var varClass: NSMutableString
    var varStruct: String
    
    let letClass: NSMutableString
    let letStruct: String
    
    init(_ c: NSMutableString, _ s: String) {
        varClass = c
        varStruct = s
        
        letClass = c
        letStruct = s
    }
    
    
    //mutating function block
    func function() {
//            varClass = "SECONDARY propertyClass" //Cannot assign to property: 'self' is immutable
//            varStruct = "SECONDARY propertyStruct" //Cannot assign to property: 'self' is immutable
    }

    mutating func mutatingFunction() {
        varClass = "SECONDARY propertyClass"
        varStruct = "SECONDARY propertyStruct"
    }
}

Possible use cases

func functionVarLetClassStruct() {
    
    var varMyClass = MyClass("propertyClass", "propertyStruct")
    
    varMyClass.varClass = "SECONDARY propertyClass"
    varMyClass.varStruct = "SECONDARY propertyStruct"
    
//        varMyClass.letClass = "SECONDARY propertyClass" //Cannot assign to property: 'letClass' is a 'let' constant
//        varMyClass.letStruct = "SECONDARY propertyStruct" //Cannot assign to property: 'letStruct' is a 'let' constant
    
    let letMyClass = MyClass("propertyClass", "propertyStruct")
    
    letMyClass.varClass = "SECONDARY propertyClass"
    letMyClass.varStruct = "SECONDARY propertyStruct"
    
//        letMyClass.letClass = "SECONDARY propertyClass" //Cannot assign to property: 'letClass' is a 'let' constant
//        letMyClass.letStruct = "SECONDARY propertyStruct" //Cannot assign to property: 'letStruct' is a 'let' constant
    
    var varMyStruct = MyStruct("propertyClass", "propertyStruct")
    
    varMyStruct.varClass = "SECONDARY propertyClass"
    varMyStruct.varStruct = "SECONDARY propertyStruct"
    
//        varMyStruct.letClass = "SECONDARY propertyClass" //Cannot assign to property: 'letClass' is a 'let' constant
//        varMyStruct.letStruct = "SECONDARY propertyStruct" //Cannot assign to property: 'letStruct' is a 'let' constant
    
    let letMyStruct = MyStruct("propertyClass", "propertyStruct")
    
//        letMyStruct.varClass = "SECONDARY propertyClass" //Cannot assign to property: 'letMyStruct' is a 'let' constant
//        letMyStruct.varStruct = "SECONDARY propertyStruct" //Cannot assign to property: 'letMyStruct' is a 'let' constant
    
//        letMyStruct.letClass = "SECONDARY propertyClass" //Cannot assign to property: 'letClass' is a 'let' constant
//        letMyStruct.letStruct = "SECONDARY propertyStruct" //Cannot assign to property: 'letStruct' is a 'let' constant
    
}

mutating - Mutating Struct's Functions

You can mark a struct's method as mutating

  1. Indicates that this function changes internal property values
  2. You are only able to call mutating function on var variable
  3. Result is visible when mutating function is finished
func testStructMutatingFunc() {
    //given
    var varMyStruct = MyStruct("propertyClass", "propertyStruct")
    
    //when
    varMyStruct.mutatingFunction()
    
    //than
    XCTAssert(varMyStruct.varClass == "SECONDARY propertyClass" && varMyStruct.varStruct == "SECONDARY propertyStruct")
    
    // It is not possible to call a mutating function on a let variable
    let letMyStruct = MyStruct("propertyClass", "propertyStruct")
//        letMyStruct.mutatingFunction() //Cannot use mutating member on immutable value: 'letMyStruct' is a 'let' constant
}

inout inside a function

  1. inout allows you to reassign/modify a passed(original) value.
  2. You are only able to pass var variable inside inout parameter
  3. Result is visible when function is finished

inout has a next flow:

  1. passed value is copied into copied value before a function called
  2. copied value is assign into passed value after the function finished
//InOut
func functionWithInOutParameter(a: inout MyClass, s: inout MyStruct) {
    
    a = MyClass("SECONDARY propertyClass", "SECONDARY propertyStruct") //<-- assign
    s = MyStruct("SECONDARY propertyClass", "SECONDARY propertyStruct") //<-- assign
}


func testInOutParameter() {

    //given
    var varMyClass = MyClass("PRIMARY propertyClass", "PRIMARY propertyStruct")
    var varMyStruct = MyStruct("PRIMARY propertyClass", "PRIMARY propertyStruct")

    //when
    functionWithInOutParameter(a: &varMyClass, s: &varMyStruct)

    //then
    XCTAssert(varMyClass.varClass == "SECONDARY propertyClass" && varMyClass.varStruct == "SECONDARY propertyStruct")
    XCTAssert(varMyStruct.varClass == "SECONDARY propertyClass" && varMyStruct.varStruct == "SECONDARY propertyStruct")
    
    
    // It is not possible to pass let into inout parameter
    let letMyClass = MyClass("PRIMARY propertyClass", "PRIMARY propertyStruct")
    let letMyStruct = MyStruct("PRIMARY propertyClass", "PRIMARY propertyStruct")
//        functionWithInOutParameter(a: &letMyClass, s: &letMyStruct) //Cannot pass immutable value as inout argument: 'letMyClass', 'letMyStruct' are 'let' constants
}     

*You steal are able to mutate let + struct

func testStructMutability()  {
    //given
    let str: NSMutableString = "propertyClass"
    let letMyStruct = MyStruct(str, "propertyStruct")
    
    //when
    str.append(" SECONDARY")
    
    //then
    XCTAssert(letMyStruct.letClass == "propertyClass SECONDARY")
}

Use let whenever you can. Use var when you must.

[Mutate structure]

Poliomyelitis answered 6/12, 2019 at 19:23 Comment(0)
A
17

let is used to define constants and var to define variables.

Like C, Swift uses variables to store and refer to values by an identifying name. Swift also makes extensive use of variables whose values can’t be changed. These are known as constants, and are much more powerful than constants in C. Constants are used throughout Swift to make code safer and clearer in intent when you work with values that don’t need to change.

https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html

Alicyclic answered 2/6, 2014 at 20:30 Comment(0)
A
9

It's maybe better to state this difference by the Mutability / Immutability notion that is the correct paradigm of values and instances changeability in Objects space which is larger than the only "constant / variable" usual notions. And furthermore this is closer to Objective C approach.

2 data types: value type and reference type.

In the context of Value Types:

'let' defines a constant value (immutable). 'var' defines a changeable value (mutable).

let aInt = 1   //< aInt is not changeable

var aInt = 1   //< aInt can be changed

In the context of Reference Types:

The label of a data is not the value but the reference to a value.

if aPerson = Person(name:Foo, first:Bar)

aPerson doesn't contain the Data of this person but the reference to the data of this Person.

let aPerson = Person(name:Foo, first:Bar)
               //< data of aPerson are changeable, not the reference

var aPerson = Person(name:Foo, first:Bar)
               //< both reference and data are changeable.

eg:

var aPersonA = Person(name:A, first: a)
var aPersonB = Person(name:B, first: b)

aPersonA = aPersonB

aPersonA now refers to Person(name:B, first: b)

and

let aPersonA = Person(name:A, first: a)
let aPersonB = Person(name:B, first: b)

let aPersonA = aPersonB // won't compile

but

let aPersonA = Person(name:A, first: a)

aPersonA.name = "B" // will compile
Aposiopesis answered 5/6, 2014 at 22:16 Comment(2)
but if aPerson has setters you could modify its properties right? so the let doesn't make the Person immutable.Minos
Unmutability? That's inpossible! Certainly antiadvisable. I think you word you're looking for may be "immutability" :-)Hoagy
F
7

Very simple:

  • let is constant.
  • var is dynamic.

Bit of description:

let creates a constant. (sort of like an NSString). You can't change its value once you have set it. You can still add it to other things and create new variables though.

var creates a variable. (sort of like NSMutableString) so you can change the value of it. But this has been answered several times.

Folketing answered 9/3, 2015 at 6:40 Comment(0)
R
6

The

Declaring Constants and Variables section of The Swift Programming Language documentation specifies the following:

You declare constants with the let keyword and variables with the var keyword.

Make sure to understand how this works for Reference types. Unlike Value Types, the object's underlying properties can change despite an instance of a reference type being declared as a constant. See the Classes are Reference Types section of the documentation, and look at the example where they change the frameRate property.

Repeal answered 8/6, 2014 at 11:21 Comment(0)
W
5

let defines a "constant". Its value is set once and only once, though not necessarily when you declare it. For example, you use let to define a property in a class that must be set during initialization:

class Person {

    let firstName: String
    let lastName: String

    init(first: String, last: String) {
         firstName = first
         lastName = last
         super.init()
    }
}

With this setup, it's invalid to assign to firstName or lastName after calling (e.g.) Person(first:"Malcolm", last:"Reynolds") to create a Person instance.

You must define a type for all variables (let or var) at compile time, and any code that attempts to set a variable may only use that type (or a subtype). You can assign a value at run time, but its type must be known at compile time.

Wellworn answered 2/6, 2014 at 20:42 Comment(0)
B
4

let is used to declare a constant value - you won't change it after giving it an initial value.
var is used to declare a variable value - you could change its value as you wish.

Bruiser answered 4/6, 2014 at 13:39 Comment(0)
J
2

One more difference, which I've encountered in other languages for Constants is : can't initialise the constant(let) for later , should initialise as you're about to declare the constant.

For instance :

let constantValue : Int // Compile error - let declarations require an initialiser expression

Variable

var variableValue : Int // No issues 
Johnnyjohnnycake answered 10/6, 2014 at 10:5 Comment(1)
This isn't quite true. In a function I can have the following: let num: Int followed by: if someCondition { num = 42 } else { num = 100 }. As long as there is no other code between the declaration and the lines of code that give it a value, it can be split across lines.Instruct
M
1

let is used to define constants and var to define variables. You define the string using var then particular String can be modified (or mutated) by assigning it to a variable (in which case it can be modified), and if you define the string using let its a constant (in which case it cannot be modified):

var variableString = "Apple"
variableString += " and Banana"
// variableString is now "Apple and Banana"

let constantString = "Apple"
constantString += " and another Banana"
// this reports a compile-time error - a constant string cannot be modified
Midwinter answered 2/7, 2014 at 6:55 Comment(0)
C
1

in swift language let is a constant means is can not reassign but var can be reassigned

let question = "what is the difference between let and var?"

question = "another question" // this line cause syntax error

var answer = "let is constant and var is simple variable"

answer = "let can't be reassigned var can be reassigned" // this line will be excecuted

Confiding answered 2/1, 2022 at 11:28 Comment(0)
P
0

A value can be reassigned in case of var

 //Variables
 var age = 42
 println(age) //Will print 42
 age = 90
 println(age) //Will Print 90

** the newAge constant cannot be reassigned to a new value. Trying to do so will give a compile time error**

//Constants
let newAge = 92 //Declaring a constant using let
println(newAge) //Will print 92.
Peterkin answered 3/6, 2014 at 4:19 Comment(0)
H
0

“Use let to make a constant and var to make a variable”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

Huffy answered 14/6, 2014 at 0:31 Comment(0)
P
0

let is a constant value, so it can never be changed.

let number = 5  
number = 6               //This will not compile.

Var is a variable, and can change (but after it is defined not to a different data type.)

var number = 5
number = 6               //This will compile.

If you try changing the variable to a different dataType, it will not work

var number = 5
number = "Hello World"   //This will not compile.
Pitchdark answered 16/10, 2014 at 4:22 Comment(1)
Let should be let.Intoxicating
C
0

let keyword defines a constant

let myNum = 7

so myNum can't be changed afterwards;

But var defines an ordinary variable.

The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once.

You can use almost any character you like for constant and variable names, including Unicode characters;

e.g.

var x = 7 // here x is instantiated with 7 
x = 99 // now x is 99 it means it has been changed.

But if we take let then...

let x = 7 // here also x is instantiated with 7 
x = 99 // this will a compile time error
Contract answered 6/11, 2014 at 8:50 Comment(0)
K
0

The main difference is that var variable value can change, and let can't. If you want to have a user input data, you would use var so the value can be changed and use let datatype variable so the value can not be changed.

var str      = "dog"  // str value is "dog"
str          = "cat"  // str value is now "cat"

let strAnimal = "dog" // strAnimal value is "dog"
strAnimal     = "cat" // Error !
Kipton answered 17/11, 2014 at 23:23 Comment(1)
Let and Var is not Working using (let and var) in small letter.Pupiparous
I
0

Like Luc-Oliver, NullData, and a few others have said here, let defines immutable data while var defines mutable data. Any func that can be called on the variable that is marked mutating can only be called if it is a var variable (compiler will throw error). This also applies to func's that take in an inout variable.

However, let and var also mean that the variable cannot be reassigned. It has two meanings, both with very similar purposes

Ize answered 16/2, 2015 at 6:20 Comment(0)
P
0

var value can be changed, after initialization. But let value cannot be changed when it is initialized once.

In case of var

  function variable() {
     var number = 5, number = 6;
     console.log(number); // return console value is 6
  }
  variable();

In case of let

   function abc() {
      let number = 5, number = 6;
      console.log(number); // TypeError: redeclaration of let number
   }
   abc();
Pupiparous answered 25/3, 2015 at 5:21 Comment(2)
But let value is not be change, when it is intilize once. I do not agree with this. Your comment is fine with non object values like int, float. But try with an mutable array and mutable string, You can change their values by adding or appending values. The correct is let objects can not be change by its pointer their pointer address will be always same thats why you are getting reinitialise error. So you can say let makes const pointer which can not be change in future.Intoxicating
There is no console.log in Swift. Check the OP's tagFortitude
G
0

Everyone has pretty much answered this but here's a way you can remember what's what

Let will always say the same think of "let" as let this work for once and always as for "var" variable's can always change hence them being called variable's

Gonorrhea answered 21/10, 2015 at 13:8 Comment(0)
D
0

The keyword var is used to define a variable whose value you can easily change like this:

var no1 = 1 // declaring the variable 
no1 = 2 // changing the value since it is defined as a variable not a constant

However, the let keyword is only to create a constant used when you do not want to change the value of the constant again. If you were to try changing the value of the constant, you will get an error:

let no2 = 5 // declaring no2 as a constant
no2 = 8 // this will give an error as you cannot change the value of a constant 
Damalis answered 2/12, 2015 at 13:48 Comment(0)
S
0

Let is an immutable variable, meaning that it cannot be changed, other languages call this a constant. In C++ it you can define it as const.

Var is a mutable variable, meaning that it can be changed. In C++ (2011 version update), it is the same as using auto, though swift allows for more flexibility in the usage. This is the more well-known variable type to beginners.

Seat answered 7/12, 2015 at 7:39 Comment(0)
H
0

Even though you have already got many difference between let and var but one main difference is:

let is compiled fast in comparison to var.
Hollishollister answered 3/1, 2019 at 11:26 Comment(0)
S
-1

var is the only way to create a variables in swift. var doesn't mean dynamic variable as in the case of interpreted languages like javascript. For example,

var name = "Bob"

In this case, the type of variable name is inferred that name is of type String, we can also create variables by explicitly defining type, for example

var age:Int = 20

Now if you assign a string to age, then the compiler gives the error.

let is used to declare constants. For example

let city = "Kathmandu"

Or we can also do,

let city:String = "Kathmandu"

If you try to change the value of city, it gives error at compile time.

Staal answered 10/5, 2016 at 11:27 Comment(0)
H
-1

var is variable which can been changed as many times you want and whenever

for example

var changeit:Int=1
changeit=2
 //changeit has changed to 2 

let is constant which cannot been changed

for example

let changeit:Int=1
changeit=2
 //Error becuase constant cannot be changed
Hwahwan answered 14/12, 2018 at 8:53 Comment(1)
This is a repeat of several existing answers and it does not add anything useful.Instruct
M
-2

Though currently I am still reading the manual, but I think this is very close to C/C++ const pointer. In other words, something like difference between char const* and char*. Compiler also refuses to update content, not only reference reassignment (pointer).

For example, let's say you have this struct. Take care that this is a struct, not a class. AFAIK, classes don't have a concept of immutable state.

import Foundation


struct
AAA
{
    var inner_value1    =   111

    mutating func
    mutatingMethod1()
    {
        inner_value1    =   222
    }
}


let aaa1    =   AAA()
aaa1.mutatingMethod1()      // compile error
aaa1.inner_value1 = 444     // compile error

var aaa2    =   AAA()
aaa2.mutatingMethod1()      // OK
aaa2.inner_value1 = 444     // OK

Because the structs are immutable by default, you need to mark a mutator method with mutating. And because the name aaa1 is constant, you can't call any mutator method on it. This is exactly what we expected on C/C++ pointers.

I believe this is a mechanism to support a kind of const-correctness stuff.

Mcnelly answered 3/6, 2014 at 3:44 Comment(0)
T
-2

Declare constants with the let keyword and variables with the var keyword.

let maximumNumberOfLoginAttempts = 10 var currentLoginAttempt = 0   
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0

Declare multiple constants or multiple variables on a single line, separated by commas:

var x = 0.0, y = 0.0, z = 0.0

Printing Constants and Variables

You can print the current value of a constant or variable with the println function:

println(friendlyWelcome)

Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string

Wrap the name in parentheses and escape it with a backslash before the opening parenthesis:

println("The current value of friendlyWelcome is \(friendlyWelcome)")

Reference : http://iosswift.com.au/?p=17

Toothpaste answered 5/6, 2014 at 13:38 Comment(0)
C
-2

let is used for constants that can’t be modified while var is an ordinary variable

Example:

let name = “Bob” Something like name = “Jim” will throw an error since a constant can’t be modified.

Codfish answered 18/11, 2017 at 23:49 Comment(0)
N
-2

SIMPLE DIFFERENCE

let = (can not be changed)

var = (any time update)

Nonrestrictive answered 8/3, 2019 at 6:1 Comment(1)
This appears to be just a repeat of many of the existing answers.Hinkley
T
-2

Source: https://thenucleargeeks.com/2019/04/10/swift-let-vs-var/

When you declare a variable with var, it means it can be updated, it is variable, it’s value can be modified.

When you declare a variable with let, it means it cannot be updated, it is non variable, it’s value cannot be modified.

var a = 1 
print (a) // output 1
a = 2
print (a) // output 2

let b = 4
print (b) // output 4
b = 5 // error "Cannot assign to value: 'b' is a 'let' constant"

Let us understand above example: We have created a new variable “a” with “var keyword” and assigned the value “1”. When I print “a” I get output as 1. Then I assign 2 to “var a” i.e I’m modifying value of variable “a”. I can do it without getting compiler error because I declared it as var.

In the second scenario I created a new variable “b” with “let keyword” and assigned the value “4”. When I print “b” I got 4 as output. Then I try to assign 5 to “let b” i.e. I’m trying to modify the “let” variable and I get compile time error “Cannot assign to value: ‘b’ is a ‘let’ constant”.

Triazine answered 10/4, 2019 at 16:1 Comment(0)
L
-2

The let keyword is used to declare a constant and the var keyword is used to declare a variable. Variables created with these either references, pointers or values.

Difference between them is that when you create a variable using let it will become constant upon declaration which can not modify or reassign later. In contrast, a varible with var can be assigned right away or later or noty at all. In swift, you have to be very explicit about what you are declaring.

Lamson answered 17/4, 2021 at 9:4 Comment(0)
F
-4

Found a good answer hope it can help :) enter image description here

Fowl answered 18/12, 2014 at 19:13 Comment(2)
This is actually incorrect. let does not mean that the object is immutable, it means the pointer is immutable. To get the equivalent functionality in Obj-C you need to use NSObject *const myObject = someobject; - The properties of such object can be modified, but the pointer myObject cannot be modified to point to another object.Hideaway
Totally wrong answer. Have you tried with a let array: NSMutableArray = NSMutableArray() ?? You can add and remove objects to/from this. let makes const pointer which can not be change in future but its value can be. You can not reinitialise it but can use it as you want.Intoxicating

© 2022 - 2024 — McMap. All rights reserved.