Hi
Similar question to https://forums.developer.apple.com/thread/79327?q=protocol%20codable I'm not sure if it's a bug or not.
Here is my scenario, best described in code...
import Foundation
public protocol MyProtocol : Codable {
var name: String {
get
set
}
}
public struct MyStruct : MyProtocol {
public var name: String
public var id: Int
private enum CodingKeys : String, CodingKey {
case id
case name
}
init(id: Int, name: String) {
self.id = id
self.name = name
}
/// Decode
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
}
/// Encode
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(name, forKey: .name)
}
}
public class MyClass {
public static func doSomething(completion: @escaping (MyProtocol) -> Void) {
let myStruct = MyStruct(id: 2, name: "Fred")
completion(myStruct)
}
}
MyClass.doSomething() {
(result) in
let value = try? JSONEncoder().encode(result)
guard value == nil else {
return
}
let json = String(data: value!, encoding: .utf8)
print(json)
}The error I get in playgrounds is:
Playground execution failed:
error: Samplecode.playground:43:36: error: cannot invoke 'encode' with an argument list of type '((MyProtocol))'
let value = try? JSONEncoder().encode(result)
^
Samplecode.playground:43:36: note: expected an argument list of type '(T)'
let value = try? JSONEncoder().encode(result)
If MyStruct doesn't implement init(from decoder: Decoder) or func encode(to encoder: Encoder) the compiler throws an error. So once these codable func's are implemented what is the compiler complaining about??
I've also made init(from decoder: Decoder) or func encode(to encoder: Encoder) as an extension to MyStruct, same error
Any ideas?