File (Read Text File Into String)Use Foundation, NSString and the contentsofFile argument to read a text file into a string.
This page was last reviewed on Aug 23, 2023.
File. A file contains string data. With the NSString init method, we can access this data as a string in Swift 5.8. 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.
Example code. 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.
Start We create a new string directly with this method. We must specify the contentsOfFile and an encoding.
Info We use String.encoding.ascii. Other encodings, specified in the developer documentation, are also available.
Tip We must use the try-keyword in a do-block to handle possible errors from this NSString init method.
import Foundation // Read data from this file. let path = "example.txt" do { // 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) }
Loop over file lines. 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.
Warning This approach may be inefficient for large files, as it must load the entire file into memory.
Tip The enumerateLines method safely enumerates the lines in a file. We can process them in any way.
import Foundation // File path (change this). let path = "example.txt" do { // 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 = Mario Line = Luigi Line = Goomba
Write, 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.
Then Open the "example.txt" file after you execute the program. It should contain the 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
Try keyword. The NSString init method shown above may cause an error. The file may not exist, or may not be available to the program.
Detail We use the "try" keyword in a do-block. An error will cause the do-block to be terminated early, but the program will survive.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 23, 2023 (edit).
© 2007-2023 Sam Allen.