Reading a Text File

I put the file in my project. If I don't comment out line 17 nothing compiles. I have tried a few different things but with no luck yet. Any pointers pardon the pun, would be great.


import SwiftUI
import Foundation

// Determine the file name
let filename = "OOMA CC Temp.txt"

// Read the contents of the specified file
let contents = try! String(contentsOfFile: filename)

// Split the file into separate lines
let lines = contents.split(separator:"\n")

// Iterate over each line and print the line
func printLine()->String {
//    var oneLine: String = "Hello to all"
    var myCounter: Int = 0
    myCounter = lines.count
    myCounter += myCounter + 1
    let str1 = String(myCounter)
    return str1
}


struct CCdata : View {
    var body: some View {
        Text(printLine())
    }
}

Accepted Reply

Move your variable declarations into your 'printLine()' function, and the wrap the whole bit in a try-catch block. It may give you additional useful diagnostics. For what it's worth, it may be helpful to emply the FileManager object to ensure that the file exists at a predictable location prior to opening it (also super handy for accessing sandbox directories in a predicable way if your app is sandboxed).


func printLine() -> String {
    let filename = "OOMA CC Temp.txt"
    var str1: String
    var myCounter: Int
    do {
        let contents = try String(contentsOfFile: filename)
        let lines = contents.split(separator:"\n")
        myCounter = lines.count
        str1 = String(myCounter)
        } catch {
            return (error.localizedDescription)
        }
        return str1
}

Replies

Move your variable declarations into your 'printLine()' function, and the wrap the whole bit in a try-catch block. It may give you additional useful diagnostics. For what it's worth, it may be helpful to emply the FileManager object to ensure that the file exists at a predictable location prior to opening it (also super handy for accessing sandbox directories in a predicable way if your app is sandboxed).


func printLine() -> String {
    let filename = "OOMA CC Temp.txt"
    var str1: String
    var myCounter: Int
    do {
        let contents = try String(contentsOfFile: filename)
        let lines = contents.split(separator:"\n")
        myCounter = lines.count
        str1 = String(myCounter)
        } catch {
            return (error.localizedDescription)
        }
        return str1
}