Quick Tutorial: Write String to File Asynchronously in Swift

Muhammad Muizzsuddin
2 min readJul 7


Photo by Cathryn Lavery on Unsplash

This quick tutorial is based on article from https://www.mozzlog.com/blog/how-to-write-the-content-of-string-to-a-file-in-swift

Lets Go

So, you’re looking for an asynchronous method to save a String to a file in Swift. Apple’s provided you with a simple API in the Foundation framework for creating Strings in Swift. Simply provide the file’s path and catch any resulting errors.

Unfortunately, despite this article's title, it is not asynchronous. Sorry. The API is not async. But you can call it in an asynchronous way. If your writing will take longer than a second to complete, you can put it in a queue in the background.

Okay. Let’s just jump to the code. To see if this code works, just copy and paste it into your Xcode.

import Foundation

print("Start Write")
DispatchQueue.global(qos:.background).async {
let content = "My name is Mozzlog"
do {
try content.write(toFile: "file.txt", atomically: true, encoding:.utf8)
print("End Write")
} catch {
print("Error: \\(error)")

That is all. To write a String to a file, you simply need to invoke its write method.

Uh Snap! Error Happen!

Well, no tutorial is perfect. Do you find mistakes? Does it crash?

Perhaps the tutorial is also obsolete. Please comment below if so. Let me update it as soon as possible. Thank you very much!

Whats Next?

You can read the full article of this quick tutorial in here: https://www.mozzlog.com/blog/how-to-write-the-content-of-string-to-a-file-in-swift

You can also read another article that talks about mobile, web, and backend in https://www.mozzlog.com/blog