0

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.

enter image description here

blkpingu
  • 1,556
  • 1
  • 18
  • 41
  • You may find this useful https://stackoverflow.com/questions/43826866/read-a-file-in-a-macos-command-line-tool-project – Andrew Aug 05 '22 at 20:58
  • Adding bundles to command line applications makes them fail when compiling. Reading a file from a path in a command line application seems kind of difficult. – blkpingu Aug 05 '22 at 22:53

0 Answers0