[swift] 파일 속성 조회하기

Swift를 사용하여 파일의 속성을 조회하는 방법에 대해 알아보겠습니다.

파일 속성이란?

파일 속성은 파일에 대한 여러 정보를 포함하고 있습니다. 예를 들어 파일의 크기, 수정 날짜, 소유자 등이 파일 속성에 해당합니다.

파일 속성 조회하기

Swift에서 파일 속성을 조회하려면 FileManager 클래스를 사용해야 합니다. 다음은 파일 속성을 조회하는 간단한 예제 코드입니다.

import Foundation

let fileManager = FileManager.default
let filePath = "/path/to/file.txt" // 조회할 파일의 경로

do {
    let attributes = try fileManager.attributesOfItem(atPath: filePath) // 파일 속성 조회
    let fileSize = attributes[.size] as? UInt64 // 파일 크기
    let fileModifiedDate = attributes[.modificationDate] as? Date // 수정 날짜

    print("파일 크기: \(fileSize ?? 0)")
    print("수정 날짜: \(fileModifiedDate ?? Date())")
} catch {
    print("파일 속성 조회에 실패했습니다: \(error)")
}

위 코드에서 attributesOfItem(atPath:) 메서드를 사용하여 파일의 속성을 조회합니다. 조회한 속성은 attributes 변수에 저장되며, 파일 크기와 수정 날짜를 각각 fileSizefileModifiedDate 변수에 저장합니다.

참고 자료

위 예제 코드는 Swift 5 버전에서 작성되었습니다.