Reading and writing a string to a text file in Swift
Hello everyone! I'm a beginner in Swift and trying to figure out reading and writing strings to a text file. I've gone through tons of documentation, but I'm still confused. \n\nI need to save a small text (e.g., logs or settings) to a file, and then read it back. I tried writing something like:\n\n```swift\nlet myString = "Hello, World!"\nlet fileURL = URL(fileURLWithPath: "myFile.txt")\ntry myString.write(to: fileURL, atomically: true, encoding: .utf8)\n```\n\nBut Xcode complains about `try` without error handling. When I add `do-catch` or `try!`, the file either gets created or not — I can't find it on the disk. Same issue with reading: I write `String(contentsOf: fileURL)`, but I get a crash with the error "The file doesn’t exist".\n\nWhat am I doing wrong? How do I correctly specify the file path? Do I need to create a
No answers yet.
Log in to leave an answer