HomeSearch

Swift File (Read Text File Into String)

Use Foundation, NSString and the contentsofFile argument to read a text file into a string.

File.

A file contains string data. With the NSString init method, we can access this data as a string in Swift 3. 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.

NSString: We create a new string directly with this method. We must specify the contentsOfFile and an encoding.

Encoding: We use String.encoding.ascii. Other encodings, specified in the developer documentation, are also available.

Error: We must use the try-keyword in a do-block to handle possible errors from this NSString init method.

Swift program that uses NSString, contentsOfFile import Foundation // Read data from this file. let path = "/Users/samallen/file.txt" do { // Use contentsOfFile overload. // ... Specify ASCII encoding. // ... Ignore errors. var data = try NSString(contentsOfFile: path, encoding: String.Encoding.ascii.rawValue) // If a value was returned, print it. print(data) } Output carrots,turnips,onions,potatoes,salt Contents of file.txt: carrots,turnips,onions,potatoes,salt

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.

Lines: The enumerateLines method safely enumerates the lines in a file. We can process them in any way.

Swift program that loops over file lines import Foundation // File path (change this). let path = "/Users/samallen/file.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)") }) } Contents of file.txt: Mario Luigi Goomba Output 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 "output.txt" file after you execute the program. It should contain the string data.

Swift program that uses write toFile, writes text file import Foundation // Target path. let path = "/Users/samallen/output.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) Results: output.txt 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.

Try: 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.

Try, do

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.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.