Skip to content

Instantly share code, notes, and snippets.

@d108
Last active June 3, 2023 06:26
Show Gist options
  • Save d108/c55396207cb6a17b4e0e182acc637acf to your computer and use it in GitHub Desktop.
Save d108/c55396207cb6a17b4e0e182acc637acf to your computer and use it in GitHub Desktop.
Useful for decoding JSON data from a file by passing in a type.
/*
* SPDX-FileCopyrightText: © 2023 Daniel Zhang <https://github.com/d108/>
* SPDX-License-Identifier: MIT License
*/
import Foundation
struct DataDecoder
{
/// Generic decoder with a switch statement to handle specific types.
///
/// Usage example:
///
/// let myData: MyData? = try DataDecoder.decode(dataType: MyData.self)
///
/// - Parameter dataType: The type of data to decode.
/// - Returns: The decoded data.
static func decode<T: Codable>(dataType: T.Type) throws -> T?
{
var decodeWith: Codable.Type
let decoder = JSONDecoder()
var fileURL: URL?
switch dataType
{
// Each case is a Codable type.
case // Add any needed cases.
default:
return nil
}
if let url = fileURL, let data = try? Data(contentsOf: url)
{
return try? decoder.decode(decodeWith, from: data) as? T
}
throw DataError.decodeFailure
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment