Xcode + Swift + OS X : How do I read a file?
Hello,
I am attempting to teach myself Swift using the Xcode environment.
I have been able to create an action in the code that connects to a button push. When I attempt to read a CSV file with String(contentsOfFile: path&filename) it fails. It appears that it is a permissions issue since the file resides on my desktop. In attempt to circumvent the issue I added an empty file to the project and copied my data into it. Then attempted to use String(contentsOfFile: "Data.csv") and same with "./Data.csv" to no avail. The error is no such file or directory.
Any input on how to fix this issue would be appreciated.
Below is my action.
Regards,
Chris
@IBAction func sayButtonClicked(_ sender: Any) {
do{
let content = try String(contentsOfFile: "Data.csv")
let parsedCSV: [[CustomStringConvertible]] = content
.components(separatedBy: "\n")
.map({$0.components(separatedBy: ",")
.map({
if let floatValue = Float($0) {
return floatValue
} else {
return $0
}
})
})
print(parsedCSV)
}
catch{
print (error)
}
} // end of select button action
iMac 27″, macOS 11.4