You are running into this error because there is nno such type as PassField
, there is PassField<Int>
and PassField<String>
and you can't mix the two types in an array like that.
You could make someList
an array of AnyObject
instead, but then you'd have to do casting whenever you wanted to access an element of the list.
Maybe consider that generics might not be the proper solution here.
It's a bit more work, but you can do something like this:
public class PassField: Encodable {
public let key: String
public let value: PassFieldValue
public var optionalAttribute: String?
enum CodingKeys: CodingKey {
case key, value, attribute
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(key, forKey: .key)
switch value {
case .intValue(let val):
try container.encode(val, forKey: .value)
case .stringValue(let val):
try container.encode(val, forKey: .value)
}
if let attr = optionalAttribute {
try container.encode(attr, forKey: .attribute)
}
}
public enum PassFieldValue {
case intValue(Int)
case stringValue(String)
}
public init(key: String, value: PassFieldValue) {
self.key = key
self.value = value
}
}
var someList = [PassField]()
someList.append(PassField(key: "firstkey", value: .stringValue("A nice string")))
let p = PassField(key: "secondkey", value: .intValue(5))
p.optionalAttribute = "thing"
someList.append(p)
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
do {
let data = try encoder.encode(someList)
print(String(data: data, encoding: .utf8)!)
} catch {
print(error)
}
Result prinnted is:
[
{
"key" : "firstkey",
"value" : "A nice string"
},
{
"key" : "secondkey",
"value" : 5,
"attribute" : "thing"
}
]