In Swift, I'm trying to add a string to a URL without creating a new path component.
The only URL methods that I can find are for appending/deleting entire path components, e.g. adding a slash before the addition.
From Apple's documentation of NSURL.appendPathComponent:
Currently, I'm having to convert the URL to a String, add the bit, and then convert back to URL.
The context is: if a folder already exists, keep adding a number until you get a unique name.
myIndex = 1
let dirIndex = String(format: "d", myIndex)
var tempString = dirURL.path
tempString = dirIndex
dirURL = URL(fileURLWithPath: tempString) as URL
Surely there's an easier way?
CodePudding user response:
No, there is no easier way.
But you have to use a loop and check if the folder name plus the suffix exists, too. If so you have to remove the suffix and add a new one.
Something like this
var myIndex = 0
var dirURL = URL(fileURLWithPath: "/Users/myuser/TestFolder")
while FileManager.default.fileExists(atPath: dirURL.path) {
myIndex = 1
var path = dirURL.path
while path.last?.isNumber == true { path.popLast() }
path = String(format: "d", myIndex)
dirURL = URL(fileURLWithPath: path)
}
Or you are working with the path and create the URL at the end
var myIndex = 0
var dirPath = "/Users/myuser/TestFolder"
while FileManager.default.fileExists(atPath: dirPath) {
myIndex = 1
while dirPath.last?.isNumber == true { dirPath.popLast() }
dirPath = String(format: "d", myIndex)
}
let dirURL = URL(fileURLWithPath: dirPath)
Note: If the base folder name ends with number(s) the number(s) will be cut.
Or another approach which replaces the two trailing digits with Regular Expression. With this version the base folder name can end with number(s)
while FileManager.default.fileExists(atPath: dirPath) {
myIndex = 1
if myIndex == 1 {
dirPath = "01"
} else {
dirPath = dirPath.replacingOccurrences(of: "\\d{2}$", with: String(format: "d", myIndex), options: .regularExpression)
}
}
let dirURL = URL(fileURLWithPath: dirPath)
CodePudding user response:
you could try something easier like this:
var myIndex = 123
var dirURL = URL(fileURLWithPath: "/Users/myuser/TestFolder")
let folder = dirURL.lastPathComponent
dirURL = dirURL.deletingLastPathComponent().appendingPathComponent(folder String(myIndex))
print("\n-------> dirURL: \(dirURL) ")

