Get the modification (or creation) date of a file

Xcode 10, Swift 4.2, macOS 10.13

func fileModificationDate(url: URL) -> Date? {
do {
let attr = try FileManager.default.attributesOfItem(atPath: url.path)
return attr[FileAttributeKey.modificationDate] as? Date
} catch {
return nil

FileAttributeKey.creationDate works exactly the same; .size and .type might also be of interest.

This beautiful and elegant solution comes from this Stackoverflow answer and I wanted to save it where I’ll find it again. (I had not seen ‘return nil’ inside the catch block, but if you only care whether you’ve got a valid date, and don’t care about anything that might go wrong, that looks fine, and using the do catch block instead of _if let try?_ makes the code more readable and gives you a better clue where you might want to be more granular in production.

(Right now, I am ignoring a lot of potential errors because I need to get the application flow right)

And having found this beauty I’ve worked out that – for reasons of my file structure, it makes more sense to store creationDate and modificationDate inside my filewrapper: you cannot get a URL for a filewrapper or its contents.