Home > other >  how to create a property that counts every letter in every word in an array
how to create a property that counts every letter in every word in an array

Time:09-01

I have a @State private var usedWords = String

this array store the history of words that are used in the game

I have a property that counts the letters of every single letter in each word from the above array by using .count

I want to create a new variable that counts every letter in all the words in the above array

CodePudding user response:

You should look into the array instance method reduce. Example:

let names = ["Jessica", "Nick", "Layla", "Elanor"]
let count = names.reduce(0) { $0   $1.count }

CodePudding user response:

If you have state property your solution mb like this:

struct SomeView: View {
    @State var usedWords = [String]()
        
    var lettersCount: Int {
        usedWords.reduce(0) { $0   $1.count }
    }

    ...
}

Every change of usedWords property will trigger view redraw and recalculation of lettersCount computed property, thats why view will always use actual value of lettersCount.

  • Related