-1

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

5
  • What is "animation like cycling through words"? Commented Nov 16, 2022 at 20:46
  • 1
    Try the Apple SwiftUI Tutorials they will help you get a good start. Commented Nov 16, 2022 at 21:13
  • 1
    Text(printLine()) Commented Nov 16, 2022 at 21:15
  • 1
    The error message is pretty clear. Your text does not exist outside your printLine method. The simplest solution to your issue is to use your method result instead Text(printLine()) Commented Nov 16, 2022 at 21:20
  • 1
    ...I started learning SwiftUI without a background in Swift..., learn them the other way around, learn Swift first, then SwiftUI. Commented Nov 16, 2022 at 22:37

1 Answer 1

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.sstatic.net/PIWpC.jpg
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.