Title here
Summary here
import Foundation
func check(_ error: Error?) {
if let error = error {
fatalError(error.localizedDescription)
}
}
// Throughout program execution, we often want to create
// data that isn't needed after the program exits.
// *Temporary files and directories* are useful for this
// purpose since they don't pollute the file system over time.
// The easiest way to create a temporary file is by
// using `FileManager.default.temporaryDirectory`.
let tempDir = FileManager.default.temporaryDirectory
let tempFileURL = tempDir.appendingPathComponent("sample")
FileManager.default.createFile(atPath: tempFileURL.path, contents: nil, attributes: nil)
// Display the name of the temporary file.
print("Temp file name: \(tempFileURL.path)")
// Clean up the file after we're done. The OS is
// likely to clean up temporary files by itself after
// some time, but it's good practice to do this explicitly.
defer {
try? FileManager.default.removeItem(at: tempFileURL)
}
// We can write some data to the file.
let data = Data([1, 2, 3, 4])
try? data.write(to: tempFileURL)
// If we intend to write many temporary files, we may
// prefer to create a temporary *directory*.
let tempDirURL = try FileManager.default.url(for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: tempDir,
create: true)
print("Temp dir name: \(tempDirURL.path)")
// Clean up the directory after we're done.
defer {
try? FileManager.default.removeItem(at: tempDirURL)
}
// Now we can synthesize temporary file names by
// prefixing them with our temporary directory.
let fileURL = tempDirURL.appendingPathComponent("file1")
try? data.write(to: fileURL)
To run this Swift code, you would typically save it as a .swift
file and use the Swift compiler or run it in Xcode. Here’s an example of how you might run it from the command line:
$ swift temporary-files-and-directories.swift
Temp file name: /var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/T/sample
Temp dir name: /var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/T/com.apple.dt.Xcode.replacementItem.XXXXXX
Note that the actual paths will vary depending on your system.
In this Swift version:
FileManager.default.temporaryDirectory
to get the system’s temporary directory.FileManager.default.createFile(atPath:contents:attributes:)
.FileManager.default.url(for:in:appropriateFor:create:)
to create a temporary directory.defer
blocks to ensure cleanup of temporary files and directories.Data
type’s write(to:)
method.The overall structure and purpose of the code remain the same as the original example, demonstrating how to work with temporary files and directories in Swift.