Start learning free

LESSON 58 OF 349 · STRINGS I

String Immutability in Swift in Swift

Lesson

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.


STEP 1 OF 1
    Ctrl + Enter to check

    String Immutability in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free