Hey Folks,
I'm about two days in with Swift coming from a Java background.
So here's the issue I'm currently tackling.
I have a general class that I will be using to serialize to JSON and dispatch to a backend service.
There are entities that will be encoded that I will not know at runtime. All I care about is that they
conform to the Encodable protocol.
So I've done something like:
public class Filter : Encodable {
fileprivate var name: FilterName
fileprivate var filter: Filter?
fileprivate var filters: [Filter]?
fileprivate var filterLeft: Filter?
fileprivate var filterRight: Filter?
fileprivate var property: String?
fileprivate var value: Encodable?
fileprivate var values: [Encodable]?
fileprivate var key: Encodable?
fileprivate var from: Encodable?
fileprivate var to: Encodable?
fileprivate var pattern: String?
fileprivate var ignoreCase: Bool?
The class then conforms to the Encodable protocol with the following:
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(BASE_PACKAGE + name.rawValue, forKey: .clazz)
try container.encodeIfPresent(filter, forKey: .filter)
try container.encodeIfPresent(filterLeft, forKey: .filterLeft)
try container.encodeIfPresent(filterRight, forKey: .filterRight)
try container.encodeIfPresent(property, forKey: .property)
try container.encodeIfPresent(from, forKey: .from)
try container.encodeIfPresent(to, forKey: .to)
try container.encodeIfPresent(value, forKey: .value)
try container.encodeIfPresent(values, forKey: .values)
try container.encodeIfPresent(pattern, forKey: .pattern)
try container.encodeIfPresent(ignoreCase, forKey: .ignoreCase)
}
Everything compiles fine, but when I run the test, any attempt to process a class member of type Encodable
fails with:
EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
It appears that using Encodable at runtime like this is invalid, though I haven't clued in as to why.
Anyone have some insights to share? Is there a better approach?