skip to Main Content

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

3

Answers


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

    let names = ["Jessica", "Nick", "Layla", "Elanor"]
    let count = names.reduce(0) { $0 + $1.count }
    
    Login or Signup to reply.
  2. 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.
    Letters counting was used from JLM answer.

    Login or Signup to reply.
  3. You can do the following:

    usedWords.joined(separator: "").count
    

    Complete example:

    struct SomeView: View {
       @State var usedWords = [String]()
    
      var body: some View {
         VStack {
            Text("(usedWords.joined(separator: "").count)")
            Button {
                let words = ["Swift", "Objective C", "Kotlin", "Java", "Javascript", "Dart"]
                usedWords.append(words[Int.random(in: 0..<words.count)])
            } label: {
                Text("Add Word")
            }
        }
    }
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search