How to write to temporary file in Swift

Issue #697

Use temporaryDirectory from FileManager and String.write

func writeTempFile(books: [Book]) -> URL {
    let url = FileManager.default.temporaryDirectory
        .appendingPathComponent(UUID().uuidString)
        .appendingPathExtension("txt")
    let string = books
        .map({
            "book '\($0.url.path)'"
        })
        .joined(separator: "\n")
    try? string.write(to: url, atomically: true, encoding: .utf8)
    return url
}
Written by

I’m open source contributor, writer, speaker and product maker.

Start the conversation