Last active
June 3, 2023 06:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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