A Bit Of Geek Joy
Writing an extension this afternoon to encode some data to JSON and I finally came across an obvious place to use generics, which is something I've been eagerly waiting for. I know there are probably a ton of places I could've and should've already been using them, but I haven't really got my head around them yet. Here, though, it was obvious even to me a generic was the perfect answer.
I haven't actually tested the code yet as I was called away to dinner at the local Indian restaurant, but I look forward to testing and refining it tomorrow.
extension Encodable {
static func saveEncodedData<T: Encodable>(_ data: [T], toFilePath path: URL) {
let json = try? JSONEncoder().encode(data)
do {
try json!.write(to: path)
} catch {
print("Failed to write JSON data: \(error.localizedDescription)")
}
}
}