I want to edit a local .playground
file programmatically from my MacOS, but the usual write methods don't seem to work if the file is already created. How can I do this?
let dir = try? FileManager.default.url(
for: .desktopDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false
)
if let fileURL = dir?.appendingPathComponent("fileThatAlreadyExists").appendingPathExtension("playground") {
let outString = "Write this text to the file"
do {
try outString.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
}
The error I get is:
Failed writing to URL: file:///Users/scottlydon/Desktop/fileThatAlreadyExists.playground, Error: The file “fileThatAlreadyExists.playground” couldn’t be saved in the folder “Desktop”`.
I assume because it already exists, If I change a character in the name to be a name not yet used then it works just fine.