find the root directory of a directory in swift

To find the root directory or the absolute path of a directory in Swift, we can use the FileManager class provided by the Foundation framework. Here's the code snippet:

main.swift
let fileManager = FileManager.default
let rootPath = fileManager.currentDirectoryPath
86 chars
3 lines

currentDirectoryPath returns the absolute pathname of the current working directory of the process. This is the directory from where the app is executed, and its parent is the root directory.

We can also specify a specific directory for which we want to find the root directory. For example, if we want to find the root directory for the Documents directory of the app, we can use the following code snippet:

main.swift
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let rootPath = URL(fileURLWithPath: documentDirectoryPath).deletingLastPathComponent().path
202 chars
3 lines

Here, we first get the path of the Documents directory using NSSearchPathForDirectoriesInDomains. Then, we convert this path to a URL and remove the last path component (i.e., Documents) using deletingLastPathComponent. This gives us the parent directory, which is the root directory. Finally, we convert the URL back to a path using .path property.

With this, we can find the root directory of any directory in our app's file system.

gistlibby LogSnag