read a file in swift

To read a file in Swift, you can use the String class method called init(contentsOfFile:) which reads the contents of the file at the provided file path and returns a String.

Here's an example:

main.swift
if let filePath = Bundle.main.path(forResource: "example", ofType: "txt") {
    do {
        let fileContent = try String(contentsOfFile: filePath, encoding: .utf8)
        print(fileContent)
    } catch {
        print("Error reading file: \(error.localizedDescription)")
    }
}
281 chars
9 lines

In this example, we're using the path(forResource:ofType:) method of Bundle to get the file path of the file named "example.txt" in our app's main bundle. Then, we use the String class's init(contentsOfFile:encoding:) method to read the contents of the file into a string variable named fileContent.

If the file can't be read for some reason, such as it not existing or not having the proper encoding, the code will catch the error and print a message to the console.

gistlibby LogSnag