C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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
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: 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