Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift; Initialization of immutable value was never used

I have this simple piece of Swift code:

let message = "This is a test"

if message.range(of:"test") != nil {
    let message = "Changed string"
}

print(message)

What I want to do: If string message contains the string test, change it to Changed string. Else keep it unchanged.

I'm getting the following warning:

Initialization of immutable value 'message' was never used; consider replacing with assignment to '_' or removing it

for line

let message = "Changed string"

Also, printed output is still This is a test instead of expected Changed string.

What am I doing wrong?

like image 976
David Avatar asked Dec 02 '25 05:12

David


1 Answers

If you want it to change it, you should be making it a variable and using the same variable.

var message = "This is a test"

if message.range(of:"test") != nil {
    message = "Changed string"
}

print(message)
like image 199
Rakesha Shastri Avatar answered Dec 08 '25 10:12

Rakesha Shastri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!