run main.swift file
# Swift version 5.0.1 (swift-5.0.1-RELEASE)
$ swiftc -o main JSONLoad.swift main.swift
$ ./main
# expected output: ExampleData(name: "test")
| { | |
| "name": "test" | |
| } |
| import Foundation | |
| func load<T:Decodable>(_ filename:String, as type:T.Type = T.self) -> 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 \(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)") | |
| } | |
| } |
| struct ExampleData: Hashable, Codable { | |
| var name:String | |
| } | |
| let x:ExampleData = load("example.json") | |
| print(x) | |
| // expected output: ExampleData(name: "test") |