LAST CHANCE: Save 50% on all my Swift books and bundles! >>

Project 5.. Why does init() not work?

Forums > SwiftUI

I was wondering why startGame() does not seem to work. I know it get run and the game doesnt crash. Is there some type caveat that i dont know about? I also stepped though it with break points to double check that it was even running.

I just also noticed with init() that if you print(allWords.count) before you return that the count of allWords and rootWord is nothing. Not 0 but no output at all. Not even giving rootWord the value of silkworm.

I'm so confused on whats going on. I have dabled in programming a few times with android and kotlin but have never seen something like this before.

1      

Hi! It would be more helpful to provide a piece of code so that others could look into what might be wrong. Otherwise, we could just make guesses...

1      

import SwiftUI

struct ContentView: View {
    @State private var usedWords = [String]()
    @State private var rootWord = ""
    @State private var newWord = ""

    init() {
        startGame()
    }

    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() {
        if let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt"){
            if let startWords = try? String(contentsOf: startWordsURL) {
                let allWords = startWords.components(separatedBy: "\n")
                rootWord = allWords.randomElement() ?? "silkworm"
                return
            }
        }
        fatalError("Could not load start.txt from bundle.")
    }
}

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

1      

First not sure why you want to add init() when .onAppear(perform: startGame) works! However Have got it to work change the startGame() to this

func startGame() {
    if let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt"){
        if let startWords = try? String(contentsOf: startWordsURL) {
            let allWords = startWords.components(separatedBy: "\n")
            let pickedWord = allWords.randomElement() ?? "silkworm"
            rootWord = pickedWord
            return
        }
    }
    fatalError("Could not load start.txt from bundle.")
}

1      

@Tinywonder745

JFYI, should you have a question why to use .onAppear() over init() here is concise answer https://www.hackingwithswift.com/interview-questions/whats-the-difference-between-a-views-initializer-and-onappear

1      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.