3

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?

lucky.li
  • 31
  • 2

3 Answers3

1

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

Asperi
  • 228,894
  • 20
  • 464
  • 690
0

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
}
E.Coms
  • 11,065
  • 2
  • 23
  • 35
  • Thanks for your answering. I want to use property wrapper with codable, it should be a simple ablity. And I found test codes in swift source in github, but it can't be compiled. – lucky.li Oct 28 '19 at 06:14
  • You need to understand the definitions of protocol before you continue. – E.Coms Oct 28 '19 at 13:03
0

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
}
Bradley Mackey
  • 6,777
  • 5
  • 31
  • 45