Swift – Create Text File
To create a text file in Swift, call createFile() function on the file manager object, and pass the file path and contents to the function.
Syntax
The syntax of createFile() function is
func createFile(atPath: String, contents: Data?, attributes: [FileAttributeKey : Any]?) -> Bool
where
Parameter | Description |
---|---|
atPath | Path of the text file, we would like to create. |
contents | Content to write to the Text File. |
attributes | A dictionary containing the attributes to associate with the new file. |
createFile()
function returns a boolean value. The function returns true
if the file is created successfully. If there is any issue while creating the file, and if the file could not be created, then the function returns false
.
Example
In the following example, we will create a text file with the name test.txt in the current user home directory.
main.swift
import Foundation let filePath = NSHomeDirectory() + "/test.txt" if (FileManager.default.createFile(atPath: filePath, contents: nil, attributes: nil)) { print("File created successfully.") } else { print("File not created.") }
Output
File created successfully.
Conclusion
We have successfully created text file using createFile() function of File Manager in Swift.