Closed auctifera-josed closed 6 years ago
@auctifera-josed try this for your Contact
struct instead:
import Foundation
struct Contact {//Contact
var id: String?
var name: String?
var birthdate: Date?
//var birthdateString: String?
enum CodingKeys: String, CodingKey {
case id = "Id"
case name = "Name"
case birthdate = "Birthdate"
// WON'T COMPILE // case birthdateString = "Birthdate"
}
}
extension Contact: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decodeIfPresent(String.self, forKey: .id)
self.name = try container.decodeIfPresent(String.self, forKey: .name)
if let birthdateString = try container.decodeIfPresent(String.self, forKey: .birthdate) {
if let bdate = DateFormatter.salesforceDateFormatter.date(from: birthdateString) {
self.birthdate = bdate
}
else {
throw DecodingError.dataCorruptedError(forKey: .birthdate, in: container, debugDescription: "Date string does not match format expected by formatter.")
}
}
else {
self.birthdate = nil
}
}
}
@auctifera-josed here's another, similar example, unrelated to Salesforce: https://useyourloaf.com/blog/swift-codable-with-custom-dates/
Hi, I've been trying to work with date & datetime fields but I'm sure there is a better way and I'm hopping someone can help me out.
My struct is:
I have a query as follows
which throws the error
"Date string does not match format expected by formatter."
So I changed to a typeless query to try to use a decoder to set the date formatter as follows
which won't let me compile for the error
Cannot convert value of type 'Record' to expected argument type 'Data'
So I try to create the contact by manually getting each field data like
But the
contact.birthdate
isnil
even though thecontact.brithdateString
has a dateSo I finally end up implementing it like
which works, but seems like a lot of work for getting each date/datetime field from a query result/apex response.