Uploaded image for project: 'Swift'
  1. Swift
  2. SR-9732

Incorrect/Misleading warning for var/let in for loop

    XMLWordPrintable

    Details

    • Type: Improvement
    • Status: Resolved
    • Priority: Medium
    • Resolution: Done
    • Component/s: Compiler
    • Labels:

      Description

      Tested using LLVM f63b283c71, Clang 41ac4c4262, Swift 7cb2c9bbba:

       

      %> cat v.swift
      import Foundation
      
      func f(_ data: Data) -> Void {
         for var x in data {
            print("\(x)")
         }
      }
      %> swift v.swift
      v.swift:4:12: warning: variable 'x' was never mutated; consider changing to 'let' constant
         for var x in data {
             ~~~~^
      

      The correct solution would be to remove the "var" (which is what Xcode's Fix-It does).

       Following the advice results in:

       

      %> cat l.swift
      import Foundation
      
      func f(_ data: Data) -> Void {
         for let x in data {
            print("\(x)")
         }
      }
      %> swift l.swift
      l.swift:4:8: error: 'let' pattern cannot appear nested in an already immutable context
         for let x in data {
             ^
      

      This does not happen in REPL.

       (For reference: see my Swift Forum post)

       

      Suggested fixes:

      • Change the warning to "... consider removing 'var'" or
      • allow "let".

       

      Trivia:

      I started with the let variant, the error message was not very helpful.

        Attachments

          Activity

            People

            • Assignee:
              dingobye Ding Ye
              Reporter:
              dhoepfl Daniel Höpfl
            • Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: