Home > other >  How to fix that error “Fatal Error in ContentView.swift”?
How to fix that error “Fatal Error in ContentView.swift”?

Time:07-03

I’ve problem with fatalError(). I try to adding to a list of words but in this line there is problem it says:

fatal Error in ContentView.swift

and i don’t why this happened my code was totally correct. The code of this error:

// id were are * here* then there was a problem - trigger a cradh and report the error
    fatalError("could not load start.txt from bundle.")

And the whole code is;

import SwiftUI

struct ContentView: View {
    @State private var usedWords = [String]()
    @State private var rootWord = ""
    @State private var newWord = ""
    
    var body: some View {
        NavigationView {
            List {
                Section {
                    TextField("enter your word", text: $newWord)
                        .textInputAutocapitalization(.never)
                }
                Section {
                    ForEach(usedWords, id: \.self) { word in
                        HStack {
                            Image(systemName: "\(word.count).circle")
                            Text(word)
                        }
                    }
                }
            }
            .navigationTitle(rootWord)
            .onSubmit(addNewWord)
            .onAppear(perform: startGame)
        }
    }
    
    func addNewWord() {
        // lowercase and trim the word, to make sure we don:t add duplicate words with case differences
        let answer = newWord.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
        
        // exit if the remaining string is empty
        guard answer.count > 0 else { return }
        
        // extra validation to come
        withAnimation {
            usedWords.insert(answer, at: 0)
        }
        newWord = ""
    }
    
    func startGame() {
        // 1.find the URL for start.txt in our app bundle
        if let startWordsURL = Bundle.main.url(forResource: "start",withExtension: "txt") {
            // 2.load start.txt into a string
            if let startWords = try? String(contentsOf: startWordsURL) {
                // 3.split the string up into an array of strings, splitting on line breaks
                let allWords = startWords.components(separatedBy: "\n")
                // 4.pcik one random word, or use "yamori" as a sensible default
                rootWord = allWords.randomElement() ?? "yamori"
                
                // if we are here everything has worked, so. we can exit
                return
            }
                
        }
        // id were are * here* then there was a problem - trigger a cradh and report the error
        fatalError("could not load start.txt from   bundle.")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Any idea? How to fix that error

Thanks.

CodePudding user response:

The reason for this failing is either the url for "start.txt" is nil or try? String(contentsOf: startWordsURL) fails. In order to help you debug and become an understanding why your current code design is bad consider this design:

func startGame() {
    // 1.find the URL for start.txt in our app bundle
    guard let startWordsURL = Bundle.main.url(forResource: "start",withExtension: "txt") else{
        //assign the default value
        rootWord = "yamori"
        // if the url is not found this will print in the console
        print("File could not be found")
        return
    }
    
    do{
        // 2.load start.txt into a string
        let startWords = try String(contentsOf: startWordsURL)
        // 3.split the string up into an array of strings, splitting on line breaks
        let allWords = startWords.components(separatedBy: "\n")
        // 4.pick one random word, or use "yamori" as a sensible default
        rootWord = allWords.randomElement() ?? "yamori"
    } catch{
        //if the file couldn´t be read this will print the error in the console
        print(error)
    }
}
  • Related