3

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?

  • 1
    That’s not valid Swift syntax. You should read the [Error Handling](https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html) chapter in the Swift book. – David Rönnqvist Oct 05 '18 at 15:52
  • @DavidRönnqvist Yes, the syntax is outdated, but I'm not sure what the correct syntax is. I'll look at what you sent. –  Oct 05 '18 at 15:53

1 Answers1

7

You need to handle the possible error thrown by encapsulating the throwable function in a do-catch block. In the catch block you shouldn't throw an error, but rather parse the error thrown and decide what to do with it.

let path = bundle.path(forResource: "data", ofType: "txt")!
do {
    let string = try String(contentsOfFile: path)
} catch {
    print(error)
    // Handle the error
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • Ah, I see. This is my first time using `do` statements, thanks for the help. –  Oct 05 '18 at 16:01
  • You should use URL instead of Strings (path). `let fileURL = bundle.for(forResource: "data", withExtension: "txt")!` and then `let string = try String(contentsOf: fileURL)`. If you need the path for any reason you can always get the URL path property `fileURL.path` ` – Leo Dabus Oct 05 '18 at 16:49