0

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.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
ScottyBlades
  • 12,189
  • 5
  • 77
  • 85

1 Answers1

1

The issue there is that you are trying to overwrite a directory with a text file. Playground it is not a text file it is a directory. If you would like to save your string inside that playground "file" you would need to overwrite the "Contents.swift" file that it is located inside that playground package (directory):

let fileURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!.appendingPathComponent("fileThatAlreadyExists.playground")
let contentsURL = fileURL.appendingPathComponent("Contents.swift")

let string = """
import Cocoa
var str = "Yes it works"
"""
do {
    try Data(string.utf8).write(to: contentsURL, options: .atomic)
} catch {
    print("Error:", error)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571