Daniel Tull: Today I Learned

How to prevent failure when attempting to create a directory that already exists

Thursday, 01 December 2022

The following FileManager method can be used to create a directory:

func createDirectory(
    at url: URL,
    withIntermediateDirectories createIntermediates: Bool,
    attributes: [FileAttributeKey : Any]? = nil
) throws

Daniel Kennett made me aware recently that if you pass true for the createIntermediates parameter, the call will suceed if the directory you’re trying to create already exists.

The documentation for this is not part of the createIntermediates parameter, but instead shown in the section about the return value:

true if the directory was created, true if createIntermediates is set and the directory already exists, or false if an error occurred.

This was really helpful for my FileBuilder project, which tries to use the existing file hierarchy if at all possible.