Swift – the different between `if var` and `if let` in swift?

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.

Best Solution

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.