Learn Courses My Dashboard

Trying to read a text file

Trying to read a text file 1 line at a time and append each line to string array “text”

Button(“Read File”) {
let path = Bundle.main.path(forResource: “TextFile”, ofType: “txt”)!
let text = try! String(contentsOfFile: path, encoding: String.Encoding.utf8)

                let range = text.startIndex ..< text.endIndex
                var lines = [String]()
                text.enumerateSubstrings(in: range, options: String.EnumerationOptions.byLines) {
                    (substring, range, enclosingRange, stop) in
                    guard let substring = substring else { return }
                n4 = text[0]    Cannot assign value of type Character tp type string

at the top I have @State var n4 = “”

That seems like way too much work for the task. How are your lines delineated? If it’s by \n, why not just do something like this:

let url = Bundle.main.url(forResource: "TextFile", withExtension: "txt")!
let text = try! String(contentsOf: url)
let lines = text.split(separator: "\n")