Working with Directories in Swift
Discover how to write Swift code to interact with file systems, including changing, creating, and deleting directories.
We'll cover the following...
The goal of this lesson is to provide an overview of how to work with local file system directories. Topics covered include identifying the user’s document and temporary directories, finding the current working directory, creating, removing and renaming directories, and obtaining listings of a directory’s content. Once the topic of directory management has been covered, we will move on to handling files in the next lesson.
The FileManager, FileHandle, and Data classes
The Foundation Framework provides three classes that are indispensable when it comes to working with files and directories:
• FileManager : The FileManager class can be used to perform basic file and directory operations, such as creating, moving, reading and writing files and reading and setting file attributes. In addition, this class provides methods for (amongst other tasks) identifying the current working directory, changing to a new directory, creating directories, and listing the contents of a directory.
• FileHandle : The FileHandle class is provided for performing lower-level operations on files, such as seeking to a specific position in a file and reading and writing a file’s contents by a specified number of byte chunks and appending data to an existing file.
• Data : The Data class provides a useful storage buffer where the contents of a file may be read or from which dynamically stored data may be written to a file.
All of these classes are part of the Foundation
framework which must be imported when working with files and directories:
import Foundation
Understanding pathnames in Swift
Swift defines pathnames using the standard UNIX convention. As such, each component of a path is ...