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?
let
within the conditional block as it has already been declared. Also, it should bevar
anyway so you can change it. – Chrislet
inside theif
statement means you are actually declaring a second variable, not replacing the value of the first. – dfdmessage.range(of:"test").map { _ in message = "Changed string" }
;D (given, naturally, thatmessage
is mutable:var message = "This is a test"
) – dfrib