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.swift281 chars9 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