Get the nth character from a string in Swift


In this Swift programming tutorial, you are going to see how to get the nth character from a string.

To get the character from the N position, we are going to use the index() method. This method will get the position index from our string by index number.

Before describing further, let’s see the code below:

let fruit = "Strawberry"

// Get a character of N position
let index = fruit.index(fruit.startIndex, offsetBy: 3)
let startChar = fruit[index] // returns Character 'u'
print(startChar)

Output:

a

In the above example, we first used the string index() method to get the index position of our string by providing the index number. In our case, we have used the index number 3. After that, we pass the index to our array to get the character from the position at 3 of the Swift string.

In our code, we have set the offsetBy 3. If you want to get the character from the position 4, then you have to set the offsetBy to 4:

fruit.index(fruit.startIndex, offsetBy: 3)

This is how it works.