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.
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!)
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
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))
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])
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) print(char)