Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the different between `if var` and `if let` in swift? [duplicate]

Tags:

swift

Consider this two codes:

if let myValue = myObject.value as NSString?{
 //logic here
}

vs

if var myValue = myObject.value as NSString?{
 //logic here
}

I know the let keyword is define a constant, is this mean that the first line of code, if the myObject.value is NSString , the myValue constant will be made? This looks confusing.

like image 459
DNB5brims Avatar asked May 29 '15 09:05

DNB5brims


2 Answers

If you use the let then you will not be able to change myValue.

if let myValue = myObject.value as NSString? {
    myValue = "Something else" // <-- Compiler error
}

On the other hand with var you can.

if var myValue = myObject.value as NSString? {
    myValue = "Something else" // <-- It's fine
}

Please note that myValue does exists only within the scope of the if and changing its value does not produce effect outside of its scope.

Hope this helps.

like image 110
Luca Angeletti Avatar answered Oct 24 '22 12:10

Luca Angeletti


You use let to create a constant, so in the first example you cannot change myValue.

When you use var, myValue is a variable which you can change inside the if statement.

like image 20
Greg Avatar answered Oct 24 '22 13:10

Greg