0

I'm trying to loop through a string and count its characters in Swift. This code successfully outputs the character count, but I receive this warning:

warning: immutable value 'character' was never used; consider replacing with '_' or removing it for character in quote { ^~~~~~~~~ _

This is my code:

var quote = "hello there"
var count = 0

for character in quote {
  count = count + 1
}
print("\(count)")

Does anyone know why I have this warning? Also, is this the best way to approach this task? Thanks.

1 Answer 1

2

Please read the error message carefully, it tells you precisely what's wrong and what you can do.

immutable value 'character' was never used

That's indeed true, the variable character is unused. The compiler provides two fixes:

consider replacing with '_' or removing it

The latter is not an option in a loop, so use the first, replace character with an underscore

for _ in quote {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.