[swift] Swift에서 파일을 삭제하는 방법
Swift에서 파일을 삭제하는 방법은 다음과 같습니다.
- 삭제할 파일의 경로를
URL
로 변환합니다. FileManager
클래스를 사용하여 파일을 삭제합니다.
아래는 파일을 삭제하는 예제 코드입니다.
import Foundation
func deleteFile(atPath path: String) {
let fileURL = URL(fileURLWithPath: path)
do {
try FileManager.default.removeItem(at: fileURL)
print("파일이 성공적으로 삭제되었습니다.")
} catch {
print("파일 삭제에 실패했습니다. 오류: \(error.localizedDescription)")
}
}
// 사용 예시
let filePath = "/path/to/file.txt"
deleteFile(atPath: filePath)
위의 예제 코드에서는 deleteFile(atPath:)
함수를 정의하여 파일을 삭제합니다. 함수에 삭제할 파일의 경로를 문자열로 전달하면 해당 파일이 삭제됩니다. 삭제에 성공할 경우 “파일이 성공적으로 삭제되었습니다.”를 출력하고, 실패할 경우 오류 메시지를 출력합니다.
참고 문서:
- FileManager - Apple Developer Documentation
- URL - Apple Developer Documentation
- Removing Files and Directories - Apple Developer Documentation ```