Get the last character from a string in Swift


In this Swift programming tutorial, you are going to learn how to get the last character from a String. There are three methods I am going to show you that can perform this task.

Method 1: Using the last property

Using the last property is the simplest way to get the last character of a Swift string. It returns an optional value. Below is an example to get the last character of a string:

let city = "Kolkata"

print(city.last!)

Output:

a

As you can see in the above example, we have been able to get the last character from our string using the string last property. We are using the ! to convert our optional value into a string. Otherwise, it will return an optional value Optional("a").

Below is another example of using this property with if statement:

let city = "Kolkata"

if let lastChar = city.last{
    print(lastChar)
}

Output:

a

Method 2: Using the string suffix() method

Below is another example to get the last string character using the suffix() method:

let name = "Emily"

print(name.suffix(1))

Output:

y

Method 3: Using the index of last character

We can also find the last character of a string using the index of the last character. But to do that, we have to find the index of the last character using the startIndex and endIndex properties.

Below is the Swift program to find out the last character using the index of the last character:

let name = "Emily"

print(name[name.index(before: name.endIndex)])

Output:

y