Skip to content

Instantly share code, notes, and snippets.

@naxmefy
Created November 25, 2019 12:18
Show Gist options
  • Save naxmefy/490fde86190257b21b1c41efa30ee429 to your computer and use it in GitHub Desktop.
Save naxmefy/490fde86190257b21b1c41efa30ee429 to your computer and use it in GitHub Desktop.
Simple Swift JSON File Load

Simple Swift JSON loading example with typing

execute example

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")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment