Skip to content

Instantly share code, notes, and snippets.

@ytyubox
Last active May 18, 2019 09:59
Show Gist options
  • Save ytyubox/0bf52dfaa7097aff8f04fbd7e3cae53b to your computer and use it in GitHub Desktop.
Save ytyubox/0bf52dfaa7097aff8f04fbd7e3cae53b to your computer and use it in GitHub Desktop.

file io in swift

Make a file

#!/bin/bash
touch the/path/to/file
#!/bin/swift
if FileManager.default.fileExists(atPath: "the/path/to/file") {
  fputs("file existed", stderr)
}else{
  try "".write(to: URL(fileURLWithPath: "123"),
               atomically: false,
               encoding: .utf8)
}

Write to a file

#!/bin/bash
echo 'String' > the/path/to/file #Creat and add 'String' into it
echo 'Second String' >> the/path/to/file
echo 'Replaced String' > the/path/to/file
#!/bin/swift
let dataToWrite:Date = ...
try dataToWrite.write(to URL(fileURLWithPath: "the/path/to/file"))

// appending a.k.a. shell(>>)
 let handle = try FileHandle(forWritingTo: URL(fileURLWithPath: path))
            handle.seekToEndOfFile()
            handle.write(data)
            handle.closeFile()

Reading a file

#!/bin/bash
cat the/path/to/file 
#!/bin/swift
let data = try Data(contentsOf: URL(fileURLWithPath: "the/path/to/file"))

Delete a File

#!/bin/bash
rm the/path/to/file
#!/bin/swift
try fileManager.removeItem(atPath: "the/path/to/file")
@ytyubox
Copy link
Author

ytyubox commented May 18, 2019

I highly recommend using Files, which is really good!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment