Search code examples
ioswarningsswift2ios9xcode7

if let warning in Swift 2.0


Swift 2.0 is throwing warnings

Immutable value 'a' was never used; Consider replacing it with '_' or removing it

Is it fine to replace the if-let with "_" ?

if let a = responseString {  
    //Code
}

Solution

  • It means that the code never accessed / used the constant "let a" inside the if- block.

    Probably you don't need the if-block at all if you do not need to access "let a". Maybe you used responseString! instead? Or do you only want to execute your code if the responseString is not nil (a simple if responseString != nil would do it then)?

    After the if-block, the "let a" a will be marked for garbage collection or marked to be deleted after the if block during compile time (not sure about that).

    Thus the compiler thinks that it is a good idea to replace the condition, as the assignment

    let a = responseString 
    

    will result in false if

    responseString == nil
    

    and true in all other cases.

    This condition-assignment is used in 99% of the cases to assure that e.g. the nillable variable responseString is not nil or even more often to automatically unwrap it on-the-fly.