5

How can I create an empty file in Swift code, preferably avoiding the Terminal, in as few lines of code as possible? I am using Swift 4, Xcode 9.4.1 and macOS High Sierra. I have tried using the Terminal to run Bash code, see my post here.

Edit:
The question this ones' been marked as duplicate for is for the terminal, which I am trying to avoid now, read that question (which I wrote) to see why.

Edit 2:
If the file already exists, I wish for the code to raise an error to the user, and the code will display it with NSTextField or UILabel.

Thanks in advance!

Benj
  • 736
  • 7
  • 21
  • Possible duplicate of [Create file in Bash Terminal from Swift](https://stackoverflow.com/questions/52226934/create-file-in-bash-terminal-from-swift) – Scriptable Sep 10 '18 at 11:07
  • 2
    `FileManager.default.createFile(atPath: fileURL.path, contents: nil, attributes: nil)` – Leo Dabus Sep 10 '18 at 11:08
  • 1
    @LeoDabus: According to the discussion in https://forums.developer.apple.com/thread/97497, `Data.write(to:)` is preferred over `FileManager.default.createFile(atPath:)`, because it takes an URL and throws an error in the failure case (instead of just returning a boolean) – Martin R Sep 10 '18 at 11:10
  • @MartinR Thats what I usually use here. But thanks anyway – Leo Dabus Sep 10 '18 at 11:12
  • 1
    @LeoDabus: Although: they behave differently if the file already exists. I wonder why there is no `FileManager.create(at: URL) throws` method. – Martin R Sep 10 '18 at 11:15
  • 1
    @Benj: What would be the intended behavior if the file already exists? Print an error message? Overwrite with an empty file? Update the modification date? Do nothing? – Martin R Sep 10 '18 at 11:17
  • @MartinR I guess to display an error message to the user, UILabel or NSTextField style. – Benj Sep 11 '18 at 08:52
  • @Benj: I suggest to add that information to the question itself. – Martin R Sep 11 '18 at 08:54

1 Answers1

5

Using your script in the linked question, try:

shell("touch file.txt")

The command touch will create the file file.txt.

You do not need the terminal for anything here, just run your .swift file and you will have your file.

In case you need the file to write to, just use something like this:

let url = URL(fileURLWithPath: "file.txt")
try "Some string".write(to: url, atomically: true, encoding: .utf8)

You file file.txt will contain the string "Some string" in it.

Update

AFAIK it is not possible to just create a file, but you could create a file with an empty string:

try "".write(to: url, atomically: true, encoding: .utf8)

As mentioned by OP in comment, it is also necessary to disable sandboxing: Remove Sandboxing

regina_fallangi
  • 2,080
  • 2
  • 18
  • 38