Avatar ·

Reading and writing a string to a text file in Swift

Hello everyone! I'm new to Swift and trying to figure out reading and writing strings to text files. I've tried a bunch of options from the internet, but I keep getting errors or nil.\n\nHere's what I tried:\n\n```swift\nlet path = "/Users/me/Documents/test.txt"\nlet content = try String(contentsOfFile: path)\nprint(content)\n```\n\nIt gives an error: "The file couldn’t be opened because there is no such file."\n\nAnd for writing I did this:\n\n```swift\nlet text = "Hello, world!"\ntry text.write(toFile: path, atomically: true, encoding: .utf8)\n```\n\nAlso an error: "You don’t have permission to save the file."\n\nI tried using FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first, but I'm still confused. Tell me how to properly read and write strings to text files.