[swift] Swift에서 디렉토리 삭제와 복구 기능 구현하기

Swift를 사용하여 디렉토리를 삭제하고, 복구하는 기능을 구현하는 방법에 대해 알아보겠습니다. 이 기능을 구현하기 위해서는 FileManager 클래스를 사용하여 파일 시스템 작업을 수행합니다.

디렉토리 삭제하기

먼저, 디렉토리를 삭제하는 방법에 대해 알아보겠습니다. 다음은 Swift에서 디렉토리를 삭제하는 코드 예제입니다.

import Foundation

func deleteDirectory(atPath path: String) {
    let fileManager = FileManager.default
    do {
        try fileManager.removeItem(atPath: path)
        print("디렉토리 삭제 성공")
    } catch {
        print("디렉토리 삭제 실패: \(error)")
    }
}

let directoryPath = "path_to_directory"
deleteDirectory(atPath: directoryPath)

위의 코드에서 deleteDirectory 함수는 지정된 경로의 디렉토리를 삭제합니다. FileManager 클래스의 removeItem(atPath:) 메서드를 사용하여 디렉토리를 삭제하고, 에러가 발생할 경우에 대비하여 do-catch 구문을 사용합니다.

디렉토리 복구하기

디렉토리를 삭제한 후, 복구하는 방법에 대해 알아보겠습니다. 디렉토리를 복구하기 위해서는 이전에 삭제한 디렉토리를 재생성해야 합니다.

func restoreDirectory(atPath path: String) {
    let fileManager = FileManager.default
    if !fileManager.fileExists(atPath: path) {
        do {
            try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
            print("디렉토리 복구 성공")
        } catch {
            print("디렉토리 복구 실패: \(error)")
        }
    } else {
        print("디렉토리가 이미 존재합니다")
    }
}

let deletedDirectoryPath = "path_to_deleted_directory"
restoreDirectory(atPath: deletedDirectoryPath)

restoreDirectory 함수는 지정된 경로에 디렉토리를 복구합니다. createDirectory 메서드를 사용하여 디렉토리를 재생성하고, 디렉토리가 이미 존재하는지 여부를 fileExists(atPath:) 메서드로 확인합니다.

이제 위의 예제 코드를 참고하여 Swift에서 디렉토리 삭제와 복구 기능을 구현해 보세요!

참고 자료