Swift 4 Encodable doesn't work with protocols
Originator: | aufflick | ||
Number: | rdar://33866425 | Date Originated: | Aug 13 2017 |
Status: | Open | Resolved: | |
Product: | Developer Tools | Product Version: | Xcode 9 b5 9M202q |
Classification: | It's serious man | Reproducible: | Always |
Summary: If you have a struct adopt Encodable, and one of it's properties has a protocol type (which supports Encodable), the swift compiler will complain that the protocol does not support Encodable. Steps to Reproduce: Write this amazing code into a playground in Xcode 8 b5: import Foundation protocol FooProtocol : Encodable { var foo: String { get } } struct Bar : Encodable { var bar: FooProtocol } Expected Results: Successful compilation Observed Results: Playground execution failed: error: EncodablePlayground.playground:1:8: error: type 'Bar' does not conform to protocol 'Encodable' struct Bar : Encodable { ^ EncodablePlayground.playground:2:9: note: cannot automatically synthesize 'Encodable' because 'FooProtocol' does not conform to 'Encodable' var bar: FooProtocol ^
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!
Further, explicitly adding a concrete encode function to the protocol does not help. The following also fails:
import Foundation
protocol SomeBanana : Encodable { var oops: String { get } } struct B2 : SomeBanana { var oops: String { return "After you B1" } } struct B1 : SomeBanana { var oops: String { return "After you B2" } } extension SomeBanana { func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(oops) } }
struct StripedPyjamas : Encodable { var wornBy: SomeBanana }