How to save a string to a file on disk with write(to:)

All strings have a write(to:) method that lets you save the contents of the string to disk. You need to provide a filename to write to, plus two more parameters: whether the write should be atomic, and what string encoding to use. The second parameter should nearly always be true because it avoids concurrency problems. The third parameter should nearly always be String.Encoding.utf8, which is pretty much the standard for reading and writing text.

Be warned: writing a string to disk can throw an exception, so you need to catch any errors and warn the user.

Sponsored You’re already busy updating your app for Swift 4.2 and iOS 12, so why not let Instabug help you find and fix bugs? Add just two lines of code to your project and receive comprehensive reports with all the feedback you need to ship a world-class app – click here to learn more!