Check if a string starts with a specific prefix in iOS with Swift


In this tutorial, I am going to let you know how to check if a string starts with a specific prefix string in iOS using Swift programming.

Swift already has an inbuilt method which is the hasPrefix() method. Using the hasPrefix() method, you can find out if a Swift string starts with a specified string or not.

Let’s see it with a code example below:

var myString = "Tasty Pizza"

if myString.hasPrefix("Tasty") {
    print("Starting with the prefix")
} else {
    print("Not starting with prefix")
}

Output:

Starting with the prefix

In the above code, we are using the hasPrefix() method with the if...else statement to check whether the string starts with the prefix Pizza or not.

As our string starts with the Pizza prefix, so the if...else condition run the code inside the if statement and it shows the output “Starting with the prefix”.

The returned value from the hasPrefix() method will be a boolean. It can be true or false.

If the string has the prefix with the provided string, the returned value will be true. On the other hand, if the string doesn’t have the prefix then the returned value will be false. So all we need to check is if the returned value is true or false for the given string or prefix.

Below is another example with some possibilities and the corresponding returned value for the method:

var myString = "Tasty Pizza"

print(myString.hasPrefix("Tasty")) // true
print(myString.hasPrefix("T")) // true
print(myString.hasPrefix("Tasty Pizza")) // true

print(myString.hasPrefix("Tasty Biryani")) // false
print(myString.hasPrefix("best")) // false

That’s it…

I hope, this tutorial will be helpful to you in your iOS development project. Best wishes…