diff 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
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Simoleon/Functions/Read.swift	Thu Aug 19 19:12:56 2021 +0100
@@ -0,0 +1,32 @@
+//
+//  ParseJson.swift
+//  Simoleon
+//
+//  Created by Dennis Concepción Martín on 11/07/2021.
+//
+
+import Foundation
+
+
+// Read JSON File
+func read<T: Decodable>(json filename: String) throws -> T {
+    let data: Data
+    
+    guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
+    else {
+        throw JsonErrors.fileMissing
+    }
+    
+    do {
+        data = try Data(contentsOf: file)
+    } catch {
+        throw JsonErrors.loadFailed(cause: error.localizedDescription)
+    }
+    
+    do {
+        let decoder = JSONDecoder()
+        return try decoder.decode(T.self, from: data)
+    } catch {
+        throw JsonErrors.parseFailed(cause: error.localizedDescription)
+    }
+}