0

If a member of my class AnotherClass is a of a type with codable abstract protocol the compiler fails to synthesize the coding/decoding code for the class. If instead the same member is a concrete class conforming to the same protocol then the compiler will happily synthesize the coding/decoding code. I think the second case should work, the property mp will always be a Codable concrete instance of MyProtocol, which is Codable.

/* This works */


protocol MyProtocol : Codable {

    func a(_ n : Int) -> Int

}

class MyClass : MyProtocol {
    let x = 3
    func a( _ n : Int ) -> Int {
        return n * x
    }
}

class AnotherClass : Codable {
    let y = 5
    let mp : MyClass // <---- ACTUAL CLASS
    init() {
        mp = MyClass()
    }
}

/* But this won't work. 
  Compiler error: 
  Type 'AnotherClass' does not conform to protocol 'Decodable'
  Type 'AnotherClass' does not conform to protocol 'Encodable'
*/

protocol MyProtocol : Codable {
    func a(_ n : Int) -> Int
}

class MyClass : MyProtocol {
    let x = 3
    func a( _ n : Int ) -> Int {
        return n * x
    }
}

class AnotherClass : Codable {
    let y = 5
    let mp : MyProtocol // <-------- PROTOCOL
    init() {
        mp = MyClass()
    }
 }
Jason Aller
  • 3,541
  • 28
  • 38
  • 38

1 Answers1

0

This is how you fix it.

class AnotherClass<T: MyProtocol> : Codable {
    let y = 5
    let mp : T
    init() {
        mp = MyClass() as! T // handle this more gracefully
    }
}

And use it this way

let a = AnotherClass<MyClass>()

But please consider reading this answer here. It explains a lot about why protocols behave the way they do and will help you understand more about them.

Manu
  • 21
  • 5