comparison Simoleon/Functions/Read.swift @ 150:6eac99e99b96

Add error handling to read json function
author Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com>
date Thu, 19 Aug 2021 19:12:56 +0100
parents Simoleon/Functions/ParseJson.swift@75c1a05176f6
children
comparison
equal deleted inserted replaced
149:07b5d7386e6e 150:6eac99e99b96
1 //
2 // ParseJson.swift
3 // Simoleon
4 //
5 // Created by Dennis Concepción Martín on 11/07/2021.
6 //
7
8 import Foundation
9
10
11 // Read JSON File
12 func read<T: Decodable>(json filename: String) throws -> T {
13 let data: Data
14
15 guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
16 else {
17 throw JsonErrors.fileMissing
18 }
19
20 do {
21 data = try Data(contentsOf: file)
22 } catch {
23 throw JsonErrors.loadFailed(cause: error.localizedDescription)
24 }
25
26 do {
27 let decoder = JSONDecoder()
28 return try decoder.decode(T.self, from: data)
29 } catch {
30 throw JsonErrors.parseFailed(cause: error.localizedDescription)
31 }
32 }