In this tutorial, I am going to share how to read file content example in Swift programming. This is a very basic program in Swift programming language. If you are Swift beginners or want to start learning Swift programming language, then this program will help you to understand the basic Swift programming.
Copy the below program and create a file named “SwitchProgramExample.swift” and execute it. Below is an example of swift program to read content of a file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | let fileName = "myFileName.txt" var filePath = "" // Fine documents directory on device let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager. SearchPathDirectory.documentDirectory, FileManager. SearchPathDomainMask.allDomainsMask, true) if dirs.count > 0 { let dir = dirs[0] //documents directory filePath = dir.appending("/" + fileName) print("Local path = \(filePath)") } else { print("Could not find local directory to store file") return } // Read file content. Example in Swift do { // Read file content let contentFromFile = try NSString(contentsOfFile: filePath, encoding: String.Encoding.utf8.rawValue) print(contentFromFile) } catch let error as NSError { print("An error took place: \(error)") } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.