2 ways to find the first and last character of a string in Swift

How to find the first and last character of a string in Swift:

We can get the first and last character of a string in swift in multiple ways.

Method 1: first and last properties:

first and last are defined as below:

var first: Character?
var last: Character?

Both are optional values and returns the first and the last characters of a string. Using these two, we can get the characters as below:

let givenString = "hello world"

if let firstChar = givenString.first{
    print(firstChar)
}

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

It will print :

h
d

Method 2: Using index of first and last characters:

We can use the below properties to get the first and last index of a string:

var startIndex: String.Index

var endIndex: String.Index

endIndex is actually the index after the last index. So, we need to use the below method to get the index just before it or the last index of the string:

func index(before: String.Index) -> String.Index

Using these values, we can get the first and last character of a swift string :

let givenString = "hello world"

print(givenString[givenString.startIndex])
print(givenString[givenString.index(before: givenString.endIndex)])

It will print the same output. swift first character of string

You might also like: