0

I am trying to turn a CSV file into a string to parse it and am getting very confused by the errors. The code I am using is this:

let filename = Bundle.main.path(forResource: "BaseballSimStats", ofType: "CSV")
var text = String()
do {
    text = try String(contentsOfFile: filename!, encoding: String.Encoding.utf8)
} catch {
     print("File Read Error for file \(filename!)")
}
print(text)

I am getting an error saying that the execution was interrupted because a bad instruction and that it was unexpectedly found nil while unwrapping an Optional value. This made sense because I am using filename! but when I change it to a ? I get the following error:

Playground execution failed: error: MyPlayground.playground:1:47: error: value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
text = try String(contentsOfFile: filename?, encoding: String.Encoding.utf8)
                                          ^
                                  (        )!

This is telling me to fix it by adding the !, but I get the previous error when I do that. What am I doing wrong? Thanks in advance!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
StefWG
  • 61
  • 1
  • 9

0 Answers0