Read a text file with swift

There are several posts already. But none helps me in my task. Sometimes error message appears: "The file "Text.strings" couldn't be opened using text encoding Unicode (UTF-8)." Sometimes the text is shown in strange format. Why?

import Foundation



func printLine() -> String {

    let filename = "Text"

    var text: String

    var myCounter: Int

    

    guard let file = Bundle.main.url(forResource: filename, withExtension: "strings")

    else {

        fatalError("Couldn't find \(filename) in main bundle.")

    }



    do {

        let contents = try String(contentsOf: file, encoding: String.Encoding.utf8 )

        let lines = contents.split(separator:"\n")

        print(contents)

        print(lines)

        myCounter = lines.count

        print(myCounter)

        text = String(myCounter)

        } catch {

            return (error.localizedDescription)

        }

        return text



}

This is the content of the text file:

"Text 1";
"Text 2";
"Text 3";

Sometimes error message appears: "The file "Text.strings" couldn't be opened using text encoding Unicode (UTF-8)." Sometimes the text is shown in strange format. Why?

strings is not a good extension to embed text files into an Xcode project. It may be treated as a Localized string file and may be compiled into some other format than plain text while building your project.

Please try renaming the text resource to Text.txt and see what happens.

Thanks a lot. That works.

Read a text file with swift
 
 
Q