Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from txt file in Swift 3

Tags:

file

swift

swift3

I want to know how to read from a txt file and print out specific parts of the file?

For example, "test.txt" will contain:

'''Jason 16 male self programing

Josh 15 male friend art'''

So I am looking for a way to print each word and line separately. Such as only printing:

"Jason"

"Jason is 16"

"Josh likes art"

This is what I got so far from searching around

if let filepath = Bundle.main.path(forResource: "test", ofType: "txt")
    {
        do
        {
            let contents = try String(contentsOfFile: filepath)
            print(contents[0])

        }
        catch
        {
            // contents could not be loaded
        }
    }
    else
    {
        // example.txt not found!
    }

Thank you for your support.

like image 878
JasonZhao Avatar asked Nov 26 '16 19:11

JasonZhao


1 Answers

Once you have read your file into contents you can break it into lines and words with code like:

let lines = contents.components(separatedBy: "\n")
for line in lines {
    let words = line.components(separatedBy: " ")
    print("\(words[0]) is \(words[1]) and likes \(words[4])")
}
like image 138
Jim Matthews Avatar answered Nov 15 '22 08:11

Jim Matthews