Hi, I am fairly new Xcode/Swift and am trying to load a CSV File for use in my development. I have placed the CSV file in my Assets folder but when I try to create my Data Model and load the CSV file. I run into the error: No exact matches in call to initializer. Below is the code. I have attached CSV File. Any help fixing this error would be greatly appreciated. Thanks in advance for your help.
Brian
import Foundation
import CSV
struct HospitalData: Codable { let providerNumber: String let hospital: String let address: String let city: String let state: String let zip: String let wageIndex: Double let caseMix: Double let averageCharge: Double let discharges: Int let totalCharges: Double let adjTotalCharges: Double // Add other fields as needed based on the columns in your CSV file }
func loadHospitalData() -> [HospitalData]? { guard let filePath = Bundle.main.path(forResource: "Hospital_Demographic_Data", ofType: "csv") else { print("File not found") return nil }
do {
let csv = try CSV(url: URL(fileURLWithPath: filePath))
var hospitalDataList = [HospitalData]() // Initialize as an empty array
for row in csv.namedRows {
if let providerNumber = String(row["Provider CCN"] ?? ""), // Replace "Provider CCN" with actual column name
let hospital = String(row["Hospital Name"] ?? ""), // Replace with actual column name
let address = String(row["Street Address"] ?? ""),
let city = String(row["City"] ?? ""), // Replace with actual column name
let state = String(row["State Code"] ?? ""), // Replace with actual column name
let zip = String(row["Zip Code"] ?? ""), // Replace with actual column name
let wageIndex = Double(row["Wage Index"] ?? ""),
let caseMix = Double(row["Case Max"] ?? ""),
let averageCharge = Double(row["Base Charge"] ?? ""), // Replace with actual column name
let discharges = Int(row["Medicare Discharges"] ?? ""),
let totalCharges = Double(row["Total Charges"] ?? ""),
let adjTotalCharges = Double(row["Total Wage Normalized Charges"] ?? "") { // Replace with actual column name
let hospitalData = HospitalData(
providerNumber: providerNumber,
hospital: hospital,
address: address,
city: city,
state: state,
zip: zip,
wageIndex: wageIndex,
caseMix: caseMix,
averageCharge: averageCharge,
discharges: discharges,
totalCharges: totalCharges,
adjTotalCharges: adjTotalCharges
)
hospitalDataList.append(hospitalData)
}
}
return hospitalDataList
} catch {
print("Failed to load CSV file: \(error)")
return nil
}
}
// Usage Example func main() { if let hospitalData = loadHospitalData() { for data in hospitalData { print("Hospital: (data.hospital), City: (data.city), Average Charge: (data.averageCharge)") } } }