Misleading error message when decoding a type

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.

So I just wonder if this is the intended behavior.

You should definitely file a bug about this. Diagnostic messages are intended to help you track down the source of the error, and this one isn’t doing that job well at all )-:

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

Thank you, Quinn. I will file a bug about this!

I filed a bug, but placed a link to github's gist, because Jira is really bad at displaying formatted code.

https://bugs.swift.org/browse/SR-9215

1 Like
Terms of Service

Privacy Policy

Cookie Policy