In Swift, you cannot change a single character of a string through its index: a String's subscript can only read characters (it is get-only).
For example, the following code:
var message = "Jello world"
message[message.startIndex] = "H"
does not compile: cannot assign through subscript: subscript is get-only.
Variable can still be changed:
Note that this does not mean that message cannot be changed, just that its characters cannot be replaced one at a time through an index.
Unlike strings in many other languages, a Swift string declared with var can be changed in place with methods such as append, insert or replaceSubrange. A string declared with let cannot be changed at all.
The simplest way to change message is to reassign it with a new string, like any other variable:
var message = "Jello world"
message = "Hello world"
print(message)
This code would output:
Hello world
Instead of trying to alter one character of the first string, this code gives message a whole new value ("Hello world").
Assignment
Follow the Coding Tutorial and let's practice with string immutability!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.