lucky.li
lucky.li

Reputation: 31

Swift Compilation Error for Property Wrappers with Codable in multiple files

Compilation 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 compilation failed with error:

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

How to fix it?

Upvotes: 3

Views: 309

Answers (3)

Bradley Mackey
Bradley Mackey

Reputation: 7668

Allow test to accept a generic Codable if that is the only requirement for that function:

func test<T: Codable>(_ value: T) {
    let val = value
}

Upvotes: 0

Asperi
Asperi

Reputation: 257739

It is a question of visibility... the simplest fix is just to move those helper structs into ViewController module as below... run, and all works (tested with Xcode 11.2)

enter image description here

Upvotes: 1

E.Coms
E.Coms

Reputation: 11531

The test Foo struct is not necessary to be Codable.

The test is on the bar property. and a Bool type is already comformed to Codable.

struct Foo{
    @Printed var bar: Bool = false
}

func test(_ value: Foo = Foo()) {
   var m = value
   m.bar = true. // will call didSet in @printed struct
}

Upvotes: 0

Related Questions