find the parent directory of a directory in swift

To find the parent directory of a directory in Swift, you can use the URL and Path classes from the Foundation framework. Here's an example code snippet:

main.swift
import Foundation

let directoryPath = "/path/to/directory"
let directoryURL = URL(fileURLWithPath: directoryPath)
let parentDirectoryURL = directoryURL.deletingLastPathComponent()

print(parentDirectoryURL.path)
213 chars
8 lines

In this code, we first define the path of the directory we want to find the parent directory of. We then create a URL instance from that path using the fileURLWithPath method. We then use the deletingLastPathComponent method of the URL class to get the parent directory URL. Finally, we print the path of the parent directory URL.

Note that this code assumes that the directory at directoryPath exists. If the directory doesn't exist, the deletingLastPathComponent method will return the same URL as directoryURL.

gistlibby LogSnag