Get the first character from a Swift string


This tutorial is going to show you how you can get the first character of a string in Swift programming. There are four methods listed in this tutorial that can perform this task.

Method 1: Using string first property

This is the simplest way for getting the first character of a string. Below is the given example of using the first property to get the first character from a Swift string:

let destination = "Amsterdam"

print(destination.first!)

Output:

A

As you can see in the example, we have used the !. This is because the first property returns an optional value. To get rid of the optional and get the original value, we have used !.

Method 2: Using the string prefix() method

We can also use the prefix() method to find the first character of a string. Below is an example:

let destination = "Gothenburg"

print(destination.prefix(1))

Output:

G

Method 3: Using the index of first character using startIndex

We can also get the index of the first character using the string startIndex property and use this to get the first character of our string as you can see in the example below:

let destination = "Gothenburg"

print(destination[destination.startIndex])

Output:

G

Method: 4

We also know that the first character of a string always has the index 0. So we can use the index 0 to get the first character of a String.

Below is the example, where we first create an array from the string, taking each character as each array element and get the first character using the index 0:

let destination = "Gothenburg"

let char = Array(destination)[0]
print(char)

Output:

G