UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Is there "swifty" way to solve Word Scramble challenge 5.3 ?

Forums > 100 Days of SwiftUI


import SwiftUI

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

    @State private var errorTitle = ""
    @State private var errorMessage = ""
    @State private var showError = false

    ///////////////////////// this is the block of interest
    var score:Int{
        guard !usedWords.isEmpty else {return 0}
        var newScore = 0
        for (index,word) in usedWords.enumerated(){
            newScore += index+1+word.count
        }
        return newScore
    }
    ////////////////////////

    var body: some View {
        NavigationView{
            VStack{
                TextField("Enter word", text: $newWord, onCommit: addNewWord)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding()
                    .autocapitalization(.none)
                List(usedWords, id: \.self){
                    Image(systemName: "\($0.count).circle")
                    Text($0)
                }

                Text("your score is \(score)")
            }
            .navigationBarItems(leading: Button("restart", action: startGame))
            .navigationBarTitle(rootWord)
            .onAppear(perform: startGame)
            .alert(isPresented: $showError){
                Alert(title: Text(errorTitle), message: Text(errorMessage), dismissButton: .default(Text("OK")))
            }
        }

        }

    func addNewWord(){
        let answer = newWord.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)

        guard answer.count > 0 else {
            return
        }

        guard isOriginal(word: answer) else {
            wordError(title: "Word used already", message: "be more original")
            return
        }

        guard isPossible(word: answer) else {
            wordError(title: "word not recognised", message: "you cant just make them up. you know!")
            return
        }

        guard isReal(word: answer) else {
            wordError(title: "word is not real", message: "c`mon!")
            return
        }

        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.")
    }

    func isOriginal(word: String) -> Bool{
        !usedWords.contains(word) // reverse logic
    }

    func isPossible(word:String) -> Bool{
        var tempWord = rootWord

        for letter in word{
            if let pos = tempWord.firstIndex(of: letter){
                tempWord.remove(at: pos)
            }
            else {
                return false
            }
        }
        return true
    }

    func isReal(word:String) -> Bool{
        guard word.count >= 3 && word != rootWord else {
            return false
        }
        let checker = UITextChecker()

        let range = NSRange(location: 0, length: word.utf16.count)

        let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")

        return misspelledRange.location == NSNotFound
    }

    func wordError(title:String,message:String){
        errorTitle = title
        errorMessage = message
        showError = true
    }

}

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

I broke it down via enumerated() and start assembling back counting characters.

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.