My goal is to have a field that accepts a string and the text below it will print a message with the entered word and the number of letters it contains. I have a func called 'countLetters' which takes in a parameter myWord and returns -> (Int, String). It counts the number of letters and returns that as an Int. I cant figure out how to integrate this into the struct to display on the screen.
Any advice is appreciated thanks.
import SwiftUI
struct Test1: View {
@State private var newWord = ""
var body: some View {
VStack {
TextField("Enter a word", text: $newWord)
.frame(height: 50)
.cornerRadius(10)
.background(.gray.opacity(0.1))
.padding(.horizontal, 20)
//Text(countLetters(myWord: newWord))
Text(myMessage)
}
}
}
func countLetters(myWord: String) -> (String, Int) {
var myCounter = 0
var characters = ""
for letter in myWord {
characters += "\(letter)"
myCounter += 1
}
return (characters, myCounter)
}
var myWordCount = countLetters(myWord: "Gregory")
var myMessage = "There are \(myWordCount) letters in the"
Your countLetters function is doing a bit more work than it needs to be.
var characters ends up being built into a string that is identical to myWord. You're appending every letter from the input onto characters, so it contains exactly the same data.
I'm not entirely clear why your function is returning both the string and the count.
Most importantly, there is a computed variable on String called count that already returns the number of elements in the collection (and, indeed, this property exists on all types that conform to the Collection protocol (meaning Array, Set, Dictionary, and more).
In short, your code could look something like the following (removing the extra view modifiers).
struct MyView: View {
@State private var newWord = ""
var body: some View {
VStack {
TextField("Enter a word", text: $newWord)
Text("There are \(newWord.count) letters in '\(newWord)'")
}
}
}
You may also wish to consider that Strings in Swift are UTF8 which means they can contain 'characters' from any language including things such as emojis and these characters can contain a number of bytes (up to 4). Using the String count method will ensure these are counted properly. For a great resource the actual swift manual is quite good: Strings and Characters — The Swift Programming Language (Swift 5.7). As you get more involved you should look to the string methods for manipulating Strings as it accounts for all those complexities.