I am trying to serialize a struct to a String using Swift 4\'s Encodable+JSONEncoder. The object can hold heterogenous values like String, Array, Date, Int etc.
The use
You can eliminate the EncodableValue
wrapper, and use a generic instead:
struct Bar: Encodable {
let key: String
let value: T?
var json: String {
let encoder = JSONEncoder()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E, d MMM yyyy"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
encoder.dateEncodingStrategy = .formatted(dateFormatter)
let data = try! encoder.encode(self)
return String(data: data, encoding: .utf8)!
}
}
let bar = Bar(key: "date", value: Date())
print(bar.json)
That yields:
{"key":"date","value":"Wed, 7 Feb 2018"}