Search code examples
swift3swift-playground

How to avoid "Variable j written into, but never read" in Swift?


I am using variable j to print its final value inside a defer block as shown below:

func justForFun()
{    
   defer {let x = j; print("\(x)")}
   var j = 0
   for i in 1...5
   {
       print("\(i)")
       j = i*2;
   }
}
justForFun()

So, the variable j is indeed read and printed inside the defer block. Still, PlayGround displays the warning that variable j is written, but never read. Is there a way to enlighten the compiler and to rid this warning?


Solution

  • The warning disappears if the variable declaration is moved above the defer.

    $ cat d.swift 
    func justForFun() {    
       var j = 0
       defer {let x = j; print("\(x)")}
       for i in 1...5 {
           print("\(i)")
           j = i*2;
       }
    }
    justForFun()
    
    $ swift d.swift 
    1 
    2
    3
    4
    5
    10
    

    While this doesn't explain why the warning appears, it does answer how you can make the warning go away.

    As far as enlightening the compiler, I don't think you can do that. You might want to file and issue at swift.org; see this page for how to report a bug. It seems the static flow checker is not looking at defer statements, which I believe it should. Good find.