diff Simoleon/Functions/ParseJson.swift @ 0:e0c2bda6c51f

first commit
author Dennis Concepción Martín <dennisconcepcionmartin@gmail.com>
date Sun, 11 Jul 2021 15:13:29 +0100
parents
children 75c1a05176f6
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Simoleon/Functions/ParseJson.swift	Sun Jul 11 15:13:29 2021 +0100
@@ -0,0 +1,34 @@
+//
+//  ParseJson.swift
+//  Simoleon
+//
+//  Created by Dennis Concepción Martín on 11/07/2021.
+//
+
+import Foundation
+
+
+/*
+ Read JSON File
+ */
+func parseJson<T: Decodable>(_ filename: String) -> T {
+    let data: Data
+    
+    guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
+        else {
+            fatalError("Couldn't find \(filename) in main bundle.")
+    }
+    
+    do {
+        data = try Data(contentsOf: file)
+    } catch {
+        fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
+    }
+    
+    do {
+        let decoder = JSONDecoder()
+        return try decoder.decode(T.self, from: data)
+    } catch {
+        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
+    }
+}