Swift – Read Text File

To read a Text File in Swift, we can prepare the file url and then use String initializer init(contentsOf: url) that returns file content as a string.

In this tutorial, we will learn how to read a text file.

Consider the following file, sample.txt, present in Documents folder of the user.

Swift - Read Text File - Input

In the following swift program, main.swift,

  • We are locating the folder, in this case Documents folder, using FileManager.default.urls.
  • Then appending the text file name to the folder location, using appendingPathComponent().
  • Finally, we use String() initializer method String(contentsOf: , encoding: ) to read the file contents to a string.

main.swift

import Foundation

let file = "sample.txt"

var result = ""

//if you get access to the directory
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

	//prepare file url
    let fileURL = dir.appendingPathComponent(file)

    do {
        result = try String(contentsOf: fileURL, encoding: .utf8)
    }
    catch {/* handle if there are any errors */}
}

print(result)

Run the program, and for the first time, if build is successful, you may see the following pop up in your Mac. Click on OK.

ADVERTISEMENT
Swift - Read Text File

After you click Ok, you should see the following output.

Terminal Output

Welcome to Swift Tutorial by www.tutorialkart.com!
Program ended with exit code: 0

Conclusion

In this Swift Tutorial, we learned how to read a text file to a string in Swift.