[swift] 디렉토리 재명명하기

iOS 앱을 개발하다 보면 파일 시스템에서 디렉토리의 이름을 변경해야 하는 경우가 종종 있습니다. 이번 글에서는 Swift를 사용하여 디렉토리를 재명명하는 방법에 대해 알아보겠습니다.

디렉토리 재명명하기

Swift에서 디렉토리를 재명명하기 위해서는 FileManager 클래스를 사용해야 합니다. 아래의 코드를 참고하여 디렉토리 재명명 함수를 작성해봅시다.

func renameDirectory(atPath path: String, to newName: String) -> Bool {
    let fileManager = FileManager.default
    
    guard let parentPath = URL(string: path)?.deletingLastPathComponent().path else {
        return false
    }
    
    let newPath = "\(parentPath)/\(newName)"
    
    do {
        try fileManager.moveItem(atPath: path, toPath: newPath)
        return true
    } catch {
        print("Error renaming directory: \(error)")
        return false
    }
}

위의 함수는 먼저 FileManager 인스턴스를 생성한 다음, 기존 디렉토리의 상위 경로를 추출합니다. 그리고 새로운 디렉토리 경로를 생성한 후 FileManager의 moveItem(atPath:toPath:) 메서드를 사용하여 디렉토리를 재명명합니다. 만약 오류가 발생하면 에러를 출력하고 false를 반환합니다.

사용 예시

위에서 작성한 디렉토리 재명명 함수를 사용하는 예시를 살펴봅시다.

let directoryPath = "/path/to/directory"
let newDirectoryName = "newDirectory"

if renameDirectory(atPath: directoryPath, to: newDirectoryName) {
    print("Directory renamed successfully")
} else {
    print("Failed to rename directory")
}

위의 예시에서는 /path/to/directory 경로의 디렉토리를 newDirectory로 재명명하고 있습니다. 함수가 true를 반환하면 “Directory renamed successfully”가 출력되고, false를 반환하면 “Failed to rename directory”가 출력됩니다.

결론

Swift에서 디렉토리를 재명명하는 방법에 대해 알아보았습니다. FileManager 클래스의 moveItem(atPath:toPath:) 메서드를 사용하여 디렉토리를 이동시키면서 재명명할 수 있습니다. 디렉토리 관리에 필요한 경우 이 방법을 참고하시기 바랍니다.

FileManager 클래스 문서