comparison Functions/ReadJson.swift @ 0:668fd7e0d121

first commit
author Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com>
date Tue, 05 Jan 2021 16:43:09 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:668fd7e0d121
1 //
2 // ReadJson.swift
3 // LazyBear
4 //
5 // Created by Dennis Concepción Martín on 31/12/20.
6 //
7
8 import SwiftUI
9
10 import SwiftUI
11
12 // With this function I parse the local JSON file to read it and create a list with its items.
13 let companiesData: [CompanyData] = load("companies.json")
14
15 func load<T: Decodable>(_ filename: String) -> T {
16 let data: Data
17
18 guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
19 else {
20 fatalError("Couldn't find \(filename) in main bundle.")
21 }
22
23 do {
24 data = try Data(contentsOf: file)
25 } catch {
26 fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
27 }
28
29 do {
30 let decoder = JSONDecoder()
31 return try decoder.decode(T.self, from: data)
32 } catch {
33 fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
34 }
35 }