Start learning free

LESSON 171 OF 349 · STRINGS

Strings in Swift in Swift

Lesson

The Swift String represents a sequence of characters, each identified by one index.

Creation:

To create strings in Swift, you use double quotes like this:

let greeting = "Hello"

Accessing characters:

To access the characters in a string, you use subscripting with String.Index

The following example returns the first character of a string:

let str = "Hello"
let ch = str[str.startIndex]
// ch is "H"

Getting the length:

We can get the length of a string using the .count property.

For example, to access the last character of the string, you use the last property:

let str = "Hello"
let ch = str.last!
// ch is "o"

Concatenating strings via + operator:

To concatenate two or more strings, you use the + operator:

let name = "John"
let str = "Hello " + name

print(str) // prints "Hello John"

If you want to assemble a string piece by piece, you can use the += operator:

var greet = "Welcome"
let name = "John"
greet += " to AlgoCademy, "
greet += name

print(greet) // "Welcome to AlgoCademy, John"

When concatenating many strings, it is recommended to collect them in an array and use joined() for performance

String slicing

We often want to get a substring of a string. For this, we use index-based subscripting.

Computing a range from startIndex to endIndex and subscripting returns the substring between those positions:

let str = "JavaScript"
let start = str.index(str.startIndex, offsetBy: 2)
let end = str.index(str.startIndex, offsetBy: 6)
let substr = String(str[start..<end])

print(substr) // prints "vaSc"

The startIndex is a zero-based index at which the extraction starts.

The endIndex is also zero-based index before which the extraction ends. The substr will not include the character at the endIndex index.

If you want to extract from an index to the end of the string, use an open-ended range:

let str = "JavaScript"
let start = str.index(str.startIndex, offsetBy: 4)
let substr = String(str[start...])

print(substr) // "Script"

String Immutability:

In Swift, String values declared with let are immutable, which means that they cannot be altered once created.

For example, the following code:

let myStr = "Bob"
// myStr[0] = "J" // compile error! String has no integer subscript

cannot change the value of myStr to "Job", because the contents of myStr cannot be altered.

Note that this does not mean that myStr cannot be changed, just that the individual characters of a string literal cannot be changed. The only way to change myStr would be to assign it with a new string, like this:

var myStr = "Bob"
myStr = "Job"
// or
let idx = myStr.index(myStr.startIndex, offsetBy: 1)
myStr = "J" + String(myStr[idx...])

Immutability affects performance when concatenating many strings; it is recommended to collect substrings in an array and use joined() for performance

Convert a string to an array of characters:

When we have to change characters often in a string, we want a way of doing this quickly. Because strings are immutable, we change a character by creating a whole new string, which is O(n).

But arrays are mutable and changing an element in an array is O(1). So what we can do is first convert our string to an array of characters, operate on that array and than convert the array back to a string.

We can convert a string to an array of characters using Array() like this:

var str = "Andy"
var myArr = Array(str)

// myArr is ["A", "n", "d", "y"]
myArr[0] = "a"
myArr[2] = "D"

// We convert an array of characters back to a string using String():
str = String(myArr)

print(str) // "anDy"

Iterating through the characters:

We can iterate through the elements of a string using a for-in loop like this:

let myStr = "Andy"
for ch in myStr {
    print(ch)
}

// This will print the characters "A", "n", "d" and "y" on different lines

This takes O(n) time, where n is the length of the array we iterate on.


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 7
    Ctrl + Enter to check

    Strings 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