0

I have a text file of about 30 words on individual lines called GoodWords.txt and I want to use the file as the source of an array.

I started learning Swift once SwiftUI came out, so really I started learning SwiftUI without a background in Swift.

Some great and longstanding solutions are out there on various sites including this one, but they are all in Swift not SwiftUI- so the output to print isn't helpful for me.

Here was the most useful resource: Swift Text File To Array of Strings

I finally just tried to copy and paste the version 5 one into a SwiftUI file, but I don't understand where the function should go or where to call it.

I have included the text file "GoodWords.txt" in my project. Here is my code (I'll spare you the hours of other versions that didn't work):

//
//  ImportTxtToArray.swift
//  GoodWord
//
//  Created by Gabe Mott on 11/16/22.
//

import SwiftUI

struct ImportTxtToArray: View {
    
    func printLine() -> String {
        let filename = "GoodWords"
        var text: String
        var myCounter: Int
        
        guard let file = Bundle.main.url(forResource: "GoodWords", withExtension: "txt")
                
        else {
            fatalError("Couldn't find \(filename) in 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       
    }
    
    var body: some View {
        printLine()
        Text("\(text)")
    }
}

struct ImportTxtToArray_Previews: PreviewProvider {
    static var previews: some View {
        ImportTxtToArray()
    }
}

The error I get is "Cannot find text in scope"

I'd appreciate any help with how to do this but also explanations helping me understand how to read a Swift answer and get it into SwiftUI.

That is my main question at the moment: how to get a text file into my SwiftUI file to access it as an array.

The picture / screenshot just gives the context of why I want to learn this. It's a ery rough example of the code and what I am making (BTW for my next question, I'm relying on the color variable to make the counter work, I tried to remove the color variable and everything breaks, but I digress.)

I tried lots of answers that were old (Swift 3), tried: guard, do, catch... all I got were errors. Most solutions are for much more detailed advanced situations. I am looking for the fastest most efficient way to make my text file the source for single words in my array. ultimate goal is animation like cycling through words

Gabe Mott
  • 21
  • 3

1 Answers1

0

Thanks Eli for the answer / working code! This is bulky and not final but solves the core question.

//  ImportTxtToArray.swift
//  GoodWord
//
//  Created by Gabe Mott on 11/16/22.
//

import SwiftUI

struct ImportTxtToArray: View {
    //eli helped with this, pass func but why do so many variables go here and eli put all at bottom
    @State var counter = 0
    
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    
    var body: some View {
        HStack {
            Text ("Good")
            Text("\(printLine())")
            
//            done for day , thought i could nail this:
//            Text("\(printLine[counter])")
//                .onReceive(timer) { tm in
//                    guard counter + 1 < Self.colors.count else {
//                        timer.upstream.connect().cancel()
//                        return
//                    }
//
//                    counter += 1
//                    color = Self.colors[counter]
//                }
        }
    }
    
    func printLine() -> String {
        let filename = "GoodWords"
        var text: String
        var myCounter: Int
        
        guard let file = Bundle.main.url(forResource: "GoodWords", withExtension: "txt")
                
        else {
            fatalError("Couldn't find \(filename) in bundle.")
        }
        
        do {
            let contents = try String(contentsOf: file, encoding: String.Encoding.utf8 )
            let lines = contents.split(separator:"\n")
            myCounter = lines.count
            print(myCounter)
            text = String(contents)
//            text = String(myCounter)
        } catch {
            return (error.localizedDescription)
        }
        return text
        
    }
}



  [1]: https://i.stack.imgur.com/PIWpC.jpg
Gabe Mott
  • 21
  • 3