A file contains string
data. With the NSString
init
method, we can access this data as a string
in Swift 5.9. We must specify arguments to load the file.
With contentsOfFile
, we create a string
based on the specified path. We must specify an encoding—String.encoding.ascii
works for a simple text file.
First we must import Foundation to access NSString
. Then we use a constant string
for the path. Please change the path to a file that exists on your computer.
string
directly with this method. We must specify the contentsOfFile
and an encoding.String.encoding.ascii
. Other encodings, specified in the developer documentation, are also available.import Foundation // Read data from this file. let path = "programs/example.txt" // Use contentsOfFile overload. // ... Specify ASCII encoding. // ... Ignore errors. let data = try? NSString(contentsOfFile: path, encoding: String.Encoding.ascii.rawValue) // If a value was returned, print it. print(data!)Some example text.
This program reads in a file that has three lines of text. It uses the contentsOfFile
method. It then uses enumerateLines
to iterate over the lines.
enumerateLines
method safely enumerates the lines in a file. We can process them in any way.import Foundation // File path (change this). let path = "programs/example2.txt" // Read an entire text file into an NSString. let contents = try? NSString(contentsOfFile: path, encoding: String.Encoding.ascii.rawValue) // Print all lines. contents!.enumerateLines({ (line, stop) -> () in print("Line = \(line)") })Line = Hello Line = friend Line = how Line = are Line = you
toFile
We can write a string
to a text file with the write()
toFile
function. This will create a new file if one does not already exist.
string
data.import Foundation // Target path. let path = "example.txt" // Write this text. let text = "Dante, The Divine Comedy" // Write the text to the path. try text.write(toFile: path, atomically: true, encoding: String.Encoding.ascii)Dante, The Divine Comedy
The NSString
init
method shown may cause an error. The file may not exist, or may not be available to the program.
For many important tasks in Swift, we must access the Foundation library. Swift provides helpful types like String
. But with NSString
we load strings with contentsOfFile
.