Edit: I do not believe this question is a duplicate of Read and write a String from text file. I linked that exact question in this one explaining that it did not work!
I want to be able to read a .txt
file I am including within my Xcode
project in an iOS
app. I have the following code:
let bundle = Bundle.main
override func sceneDidLoad() {
let path = bundle.path(forResource: "data", ofType: "txt")
let string = try String(contentsOfFile: path!) else throw Error
}
All the lines up until let string = ...
are fine. However, everything I have found in questions such as this one are unable to read the data.txt
file as they are incorrect/outdated syntax.
How do I read from it?
Edit: I've got the let string
to be this:
do {
let string = try String(contentsOfFile: path!)
print(string) // prints the content of data.txt
}
catch {
throw Error
}
But I still have two errors:
Thrown expression type 'Error.Protocol' does not conform to 'Error'
and
Error is not handled because the enclosing function is not declared 'throws'
How do I fix the errors?