I am trying to use data from a text file containing json data. From various sources, I was able to successfully read an array of data from the file. However, when I try to use the code outside of the function in another do, try, catch block it complains about "variable xxx used before being initialized"
Looking at an answer posted here, said to create the variable outside the do, try, catch block but it just moves the error.
swift 5 (5.7.1)
cli learning app
units.json
This is the sample json file containing an array of elements.
{
"units": [
{
"name":"cartman",
},
{
"name":"kyle",
}
]
}
fileIO.swift
This is the code to do fileIO
import Foundation
// src https://stackoverflow.com/a/36827996/1008596
struct UnitData: Decodable {
var name: String = "none"
}
struct UnitsData: Decodable {
var units: [UnitData]
}
enum JFDFileError: Error {
case FileNotFound
case JSONDecodeFailed
}
// src https://www.swiftbysundell.com/articles/working-with-files-and-folders-in-swift/
func my_simple_file_read(path: String) throws -> UnitsData {
let file_name = (path as NSString).expandingTildeInPath
let url = URL(fileURLWithPath: file_name)
// Read the file
var data: Data
do {
data = try Data(contentsOf: url)
} catch {
throw JFDFileError.FileNotFound
}
var unitsData: UnitsData
do {
let decoder = JSONDecoder()
unitsData = try decoder.decode(UnitsData.self, from: data)
// these prints work
// prints entire json file
print("entire json file \(unitsData)")
// prints specific element of json array
print("this works 0 is \(unitsData.units[1].name)")
} catch {
throw JFDFileError.JSONDecodeFailed
}
// this print works
print("this works here \(unitsData.units[1].name)")
return unitsData
}
main.swift
This is an excerpt of main code. It has same form as function but return of function call fails here. Why?
// Read units from json file
var unitsData: UnitsData
do {
unitsData = try my_simple_file_read(path: "~/somepath/units.json")
// this works
print("works1 is \(unitsData.units[1].name)")
} catch {
print("an error occured")
}
// error: Variable 'unitsData' used before being initialized
print("does not work \(unitsData.units[1].name)")