I'm trying to read *.json
into a struct
.
However I'm encountering nil
when reading the file.
struct GraphJson : Codable {
var graph: [[Int32]]
var paths: [[Int32]]
var previous: [[Int32]]
}
func readJsonFromFile(_ filename: String) -> GraphJson? {
let path = Bundle.main.url(forResource: filename, withExtension: "json")
do {
let data = try Data(contentsOf: path!) // Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
let jsonDecoder = JSONDecoder()
return try jsonDecoder.decode(GraphJson.self, from: data)
} catch {
fatalError("Unable to load \"\(filename)\" from main bundle:\n\(error)")
}
}
let graphData = readJsonFromFile("graph")!.graph
graph.json
{
"graph": [[0, 6, -1, 1, -1], [6, 0, 5, 2, 2], [-1, 5, 0, -1, 5], [1, 2, -1, 0, 1], [-1, 2, 5, 1, 0]],
"paths": [[0, 3, 7, 1, 2], [3, 0, 5, 2, 2], [7, 5, 0, 6, 5], [1, 2, 6, 0, 1], [2, 2, 5, 1, 0]],
"previous": [[0, 3, 4, 0, 3], [3, 1, 1, 1, 1], [3, 2, 2, 4, 2], [3, 3, 4, 3, 3], [3, 4, 4, 4, 4]]
}
To the best of my understanding, this should work. My file has the correct target membership and is listed the build phase under Copy Bundle Resources
.
I found multiple posts discussing this issue, and so far have not found a solution to the problem.