[swift] 파일 이동을 위한 Swift 코드 작성법

파일 이동은 Swift에서 자주 사용되는 작업 중 하나입니다. 파일을 이동하고 복사하는 방법을 알아봅시다.

파일 복사

import Foundation

let fileManager = FileManager.default
let sourceURL = URL(fileURLWithPath: "path/to/source/file")
let destinationURL = URL(fileURLWithPath: "path/to/destination/file")

do {
    try fileManager.copyItem(at: sourceURL, to: destinationURL)
} catch {
    print("Error: \(error)")
}

위의 코드에서 FileManager 클래스의 copyItem(at:to:) 메서드를 사용하여 파일을 복사합니다. 예외 처리를 통해 복사 도중 발생할 수 있는 오류를 처리합니다.

파일 이동

import Foundation

let fileManager = FileManager.default
let sourceURL = URL(fileURLWithPath: "path/to/source/file")
let destinationURL = URL(fileURLWithPath: "path/to/destination/file")

do {
    try fileManager.moveItem(at: sourceURL, to: destinationURL)
} catch {
    print("Error: \(error)")
}

위의 코드에서 FileManager 클래스의 moveItem(at:to:) 메서드를 사용하여 파일을 이동합니다. 마찬가지로 예외 처리를 통해 오류를 처리합니다.

이제 파일을 복사하고 이동하는 Swift 코드를 작성하는 방법을 배웠습니다.

더 많은 정보를 원하시면 Swift 공식 문서를 참고하세요.