[swift] Swift으로 디렉토리 생성하기 위한 함수 사용법

Swift에서 디렉토리를 생성하려면 FileManager를 사용할 수 있습니다. 아래에는 디렉토리를 생성하는 함수의 사용법에 대해 설명하겠습니다.

1. FileManager를 이용한 디렉토리 생성

FileManager를 사용하여 디렉토리를 생성하는 메서드는 createDirectory입니다. 이 메서드는 다음과 같이 사용됩니다.

let fileManager = FileManager.default
let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!

do {
    let newDirectoryURL = documentsDirectory.appendingPathComponent("NewDirectory")
    try fileManager.createDirectory(at: newDirectoryURL, withIntermediateDirectories: true, attributes: nil)
    print("디렉토리가 성공적으로 생성되었습니다.")
} catch {
    print("디렉토리 생성에 실패했습니다: \(error.localizedDescription)")
}

위의 예제에서는 FileManagercreateDirectory 메서드를 사용하여 새 디렉토리를 생성하고 있습니다. 이때 withIntermediateDirectories 매개변수를 true로 설정하면, 중간에 필요한 디렉토리도 함께 생성됩니다.

2. 디렉토리 생성 결과 확인

위와 같이 코드를 실행하면 디렉토리가 성공적으로 생성되었는지 여부를 콘솔에 출력할 수 있습니다.

이것으로 Swift에서 디렉토리를 생성하는 방법에 대한 간단한 안내를 마칩니다. 원하는 디렉토리를 생성하고 여러분의 앱 또는 프로젝트에서 활용해보세요.

참고문헌: