Read and Write String Into a Text File

In this blog post, you will learn how to read and write a string into a text file in Swift.

In the code example below, we will first write a string value into a text file and then we will read the content of that text file to see if it contains the string we have written to it. So the code below includes two examples:

  • How to write a string value into a file in Swift,
  • How to read the content of a file in Swift

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Code Example

let fileName = "myFileName.txt"
  var filePath = ""
  // Fine documents directory on device
  let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
  if dirs.count > 0 {
      let dir = dirs[0] //documents directory
      filePath = dir.appending("/" + fileName)
      print("Local path = \(filePath)")
  } else {
      print("Could not find local directory to store file")
  // Set the contents
  let fileContentToWrite = "Text to be recorded into file"
  do {
      // Write contents to file
      try fileContentToWrite.write(toFile: filePath, atomically: false, encoding: String.Encoding.utf8)
  catch let error as NSError {
      print("An error took place: \(error)")
  // Read file content. Example in Swift
  do {
      // Read file content
      let contentFromFile = try NSString(contentsOfFile: filePath, encoding: String.Encoding.utf8.rawValue)
  catch let error as NSError {
      print("An error took place: \(error)")

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.

Leave a Reply

Your email address will not be published.