Cocoa: Writing files to a macOS directory, while renaming duplicates


I want to write a bunch of files to a directory, but I don't want to overwrite files having the same name. The way I've been doing it is shown below-- first I check to see if the file name already exists, and if it does I enter a while loop appending numbers to the file name until it can't be found.

I'm just wondering if there is a better way to do this, and/or if anyone can spot something about this that is bad?


for document in documents {

   let title = document.title

   var fileName = "\(title).txt"
   var filePathToCheck = url!.appendingPathComponent(fileName).path           
   var numTimesFound: Int = 1

   while FileManager.default.fileExists(atPath: filePathToCheck) {
        numTimesFound += 1
        fileName = title +  " (" + "\(numTimesFound)" + ").txt"
        filePathToCheck = url!.appendingPathComponent(fileName).path

   let filePath = url!.appendingPathComponent(fileName)
   try document.write(to: filePath, atomically: false, encoding: .utf8)


// Given 3 documents all having the same name, produces:
// document.txt
// document (2).txt
// document (3).txt

Show source
| save   | swift   | osx   | cocoa   | swift3   2016-12-30 02:12 0 Answers

Answers ( 0 )

◀ Go back