To write to a file in Swift, you can use the FileManager
class to access the file system and then use the write
method of the Data
class to write your data to the file.
Here's an example:
main.swift460 chars18 lines
In this example, we first get a reference to the document directory using the urls(for:in:)
method of the FileManager
class. We then choose a name for our file and create a URL to it using the appendingPathComponent(_:)
method.
Next, we convert our data (a string in this case) to a Data
object using the data(using:)
method. Finally, we use the write(to:)
method to write the data to the file. Any errors that occur during the write operation are caught in the catch
block.
gistlibby LogSnag