[swift] Swift에서 디렉토리 삭제 후 다른 디렉토리로 이동하기

Swift에서 디렉토리를 삭제하고 다른 디렉토리로 이동하는 것은 일반적인 작업입니다. 이를 수행하는 방법에 대해 알아보겠습니다.

디렉토리 삭제하기

먼저, 특정 디렉토리를 삭제하는 방법을 살펴보겠습니다. Swift에서 디렉토리를 삭제하려면 FileManager 클래스를 사용합니다. 아래는 디렉토리를 삭제하는 예제 코드입니다.

import Foundation

let fileManager = FileManager.default
let directoryURL = URL(fileURLWithPath: "path_to_directory")

do {
    try fileManager.removeItem(at: directoryURL)
    print("디렉토리 삭제됨")
} catch {
    print("디렉토리 삭제 실패: \(error)")
}

위의 코드에서 "path_to_directory" 부분을 삭제하려는 실제 디렉토리 경로로 변경해주어야 합니다.

디렉토리 이동하기

디렉토리를 삭제한 후, 다른 디렉토리로 이동하려면 FileManager 클래스의 changeCurrentDirectoryPath 메서드를 사용합니다. 아래는 다른 디렉토리로 이동하는 예제 코드입니다.

let newDirectoryPath = "path_to_new_directory"

if fileManager.changeCurrentDirectoryPath(newDirectoryPath) {
    print("디렉토리 이동 성공")
} else {
    print("디렉토리 이동 실패")
}

위의 코드에서 "path_to_new_directory" 부분을 이동하고 싶은 새로운 디렉토리의 경로로 변경해주어야 합니다.

디렉토리 삭제와 이동은 파일 및 디렉토리 관리 시 자주 사용되는 작업이므로 위의 예제 코드를 참고하여 Swift 애플리케이션에서 원하는 작업을 수행할 수 있습니다.

더 자세한 내용은 Apple 공식 문서를 참고하세요.