Ad space (banner)
๐ŸฆSwift Lessons
Lesson 52 / 68

File Reading and Writing Basics

In this lesson you will learn the basics of reading and writing files in Swift, so a program can save and load text files. This is for anyone searching for "Swift file read write how to use".

A string's write(toFile:) writes to a file and String(contentsOfFile:) reads one back. Saving configuration files and logs makes this a basic operation you will use often.

The sample code saves the contents of a note with try? content.write(toFile: "memo.txt", ...), then reads the same file back with try? String(contentsOfFile: "memo.txt", encoding: .utf8). Notice how try? lets you check for failure as an Optional.

A common stumbling block for beginners is the difference between try? and try. try? lets you cope when the file is missing, but it does not tell you the details of what went wrong.

In real-world development the asynchronous APIs handle large files efficiently.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)