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

Misleading error message when decoding a type

    XMLWordPrintable

    Details

      Description

      All,

      I have encountered a misleading error message that kept me in debugging for a few minutes until I actually realized what's the problem.

      I have simplified it down to this: 

      import Foundation
      
      struct S {
          var foo: Int
          var bar: String
      }
      
      extension S: Decodable {
      
          enum CodingKeys: String, CodingKey {
              case foo, bar
          }
      
          init(from decoder: Decoder) throws {
              let container = try decoder.container(keyedBy: CodingKeys.self)
      
              foo = try container.decode(Int.self, forKey: .foo)
              
              let tmpBar = try container.decode(String.self, forKey: .bar)
      
              bar = tmpBar.map({ (char) -> String in
              //          ^--- `bar` captured by closure error here
                  return "\(char)\(foo)"
              }).joined(separator: " ")
          }
      }
      

      The problem is that I'm decoding a .bar keyed value into temporary variable tmpBar that I'm later using to derive a real bar value. And I used foo instance variable to do that. However the error message tells me that bar was actually captured by a closure before being initialised. To fix I just had to do a local copy of instance variable that I was using inside map closure.

      Please find the compressed playground attached.

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              eimantas Eimantas Vaiciunas
            • Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

              • Created:
                Updated: