Quick Tutorial: Write String to File in Swift

Muhammad Muizzsuddin
2 min readJul 7, 2023

--

Photo by Thought Catalog 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 want to know how to write a String to a file in Swift. Writing a String in Swift is easy because Apple has provided you with an easy API in the Foundation framework. You just need to supply the file path and catch the error, if any.

Without much talk. You can copy and paste this code to check how it works

import Foundation

print("Start Write")
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’s it. You just need to invoke the write method from String to write it to a file.

Uh Snap! Error Happen!

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

Maybe the tutorial is outdated too. If so, please comment below. Let me update it as soon as possible. Thank you!

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

--

--

No responses yet