Compilation Error for Property Wrappers with Codable in multiple files

I found it is compiled failed for property wrappers with codable in multiple files.

I found test codes in Swift source below:

@propertyWrapper
struct Printed<Value: Codable>: Codable {
    var wrappedValue: Value {
        didSet { print(wrappedValue) }
    }
}

struct Foo: Codable {
    @Printed var bar: Bool = false
}
func test(_ value: Foo = Foo()) {
  let _: Codable = value
}

and use them in my test project:

TestProject

But it is compiled failed with error:

Type 'Foo' does not conform to protocol 'Encodable'

How to fix it?

I found that XCode compiled successfully without codable, but compiled failed using codable.

Compile successfully:

    func test() {
        let value = Foo()
        print("test: \(value)")
        
//        // Using codable cause compilation error;
//        if let data = try? JSONEncoder().encode(value),
//            let json = String.init(data: data, encoding: .utf8) {
//            print(json)
//        }
    }

Compile failed:

    func test() {
        let value = Foo()
        print("test: \(value)")
        
        // Using codable cause compilation error;
        if let data = try? JSONEncoder().encode(value),
            let json = String.init(data: data, encoding: .utf8) {
            print(json)
        }
    }

Is it because property wrappers with codable generates codable code after compilation, but the JSONEncoder need the "Foo" struct conforms to codable protocol before compilation.

Looks like a bug, esp. that it is fixed if you move everything into 1 file. Perhaps you can file bug report.

Everything in one file is OK. I have filed a bug for XCode in https://feedbackassistant.apple.com/. I don't know it is a bug for XCode team or Swift team.

Can you try removing Codable conformance from the wrapper itself?

It is compiled failed when removing codable from wrapper itself. Because the struct "Foo" does not conform to codable protocol.

Terms of Service

Privacy Policy

Cookie Policy