Чтобы очистить текстовый файл в Swift, вы можете использовать несколько разных методов. Вот несколько примеров:
Метод 1: использование FileManager
func clearTextFileUsingFileManager(filePath: String) {
let fileManager = FileManager.default
do {
try "".write(toFile: filePath, atomically: true, encoding: .utf8)
print("Text file cleared successfully.")
} catch {
print("Error occurred while clearing the text file: \(error)")
}
}
Метод 2: использование FileHandle
func clearTextFileUsingFileHandle(filePath: String) {
let fileHandle = FileHandle(forWritingAtPath: filePath)
fileHandle?.truncateFile(atOffset: 0)
fileHandle?.closeFile()
print("Text file cleared successfully.")
}
Метод 3. Использование данных
func clearTextFileUsingData(filePath: String) {
let emptyData = Data()
do {
try emptyData.write(to: URL(fileURLWithPath: filePath))
print("Text file cleared successfully.")
} catch {
print("Error occurred while clearing the text file: \(error)")
}
}
Метод 4: использование OutputStream
func clearTextFileUsingOutputStream(filePath: String) {
if let outputStream = OutputStream(toFileAtPath: filePath, append: false) {
outputStream.open()
outputStream.write(Array<UInt8>())
outputStream.close()
print("Text file cleared successfully.")
} else {
print("Error occurred while clearing the text file.")
}
}