File. 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.
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.
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.
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 = "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
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 may cause an error. The file may not exist, or may not be available to the program.
Info We use the "try" keyword with a question mark and then we must access the inner value of the returned value with an exclamation.
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 Jan 13, 2024 (edit).