by Sai gowtham

How to get the last character from a string in Swift

To get the last character of a string, we can use the string.last property in Swift.

Here is an example that gets the last character o from a given string:

Swift
let name = "Hello Polo"
let lastCharacter  = name.last!
print(lastCharacter)

Output:

"o"

Similarly, we can also use the suffix() method by passing 1 as an argument to it.

let name = "Hello Polo"
let lastCharacter  = name.suffix(1)!
print(lastCharacter)

The suffix() method can also be used to get the last n characters from a string.

Example for getting last 3 characters:

let name = "Hello Polo"
let lastThree  = name.suffix(3)!
print(lastThree)

Output:

"olo"

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course