Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Cocoa
- class FileWriter {
- // Variables
- // For creating string filename location
- var documentPath, fileName, fullPath : String!
- // For getting the ios file manager
- var fileManager = FileManager.default
- init(fileName : String) {
- self.fileName = fileName
- fileSettings()
- }
- func fileSettings() {
- // For getting document path, we need to use our file manager...
- self.documentPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
- self.fullPath = "\(documentPath!)/\(fileName!)"
- }
- func test() {
- print(self.fullPath!)
- }
- func writeToFile(_ txt: String) {
- var myData = readFromFile()
- do {
- myData += txt
- try myData.write(toFile: self.fullPath, atomically: true, encoding: String.Encoding.utf8)
- print("Wrote to file")
- }
- catch {
- print("Error writing to file")
- }
- }
- func readFromFile() -> String {
- var temp = ""
- if fileManager.fileExists(atPath: fullPath) {
- do {
- try temp = String(contentsOfFile: fullPath)
- } catch {
- print("Cannot read from file \(self.fileName ?? "")") /// In string we can add ?? "with default content"
- }
- } else {
- print("No such file in the system")
- }
- return temp
- }
- func deleteFile() {
- do {
- try fileManager.removeItem(atPath: fullPath)
- print("File \(fileName!) deleted successfully")
- } catch {
- print("Failed to delete file \(fileName ?? "Bad file name")")
- }
- }
- }
- class SevenBoom {
- let fName = "SevenBoom.txt"
- let fileWriter = FileWriter(fileName: "SevenBoom.txt")
- var res : String = ""
- func runProc() {
- for num in 1...100 {
- if num % 7 == 0 || num % 10 == 7 || num / 10 == 7 {
- res.append("Boom\n")
- } else {
- res.append("\(num)\n")
- }
- }
- }
- func createResultFile() {
- runProc()
- fileWriter.writeToFile(res)
- }
- func readResultFile() {
- print(fileWriter.readFromFile())
- }
- }
- let SBoom = SevenBoom()
- SBoom.readResultFile()
- SBoom.createResultFile()
- SBoom.readResultFile()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement