What is the hasPrefix() method in Swift?

Overview

The hasPrefix() method of a string instance in Swift checks if a string begins with a specified prefix. If true, it returns true. Otherwise, it returns false.

Syntax

string.hasPrefix(prefix)

Parameters

prefix: This is the sub-string we want to check to see if it begins the string, string.

Return value

This method returns a Boolean value. It returns a true value if the prefix string prefix begins the string string. Otherwise, it returns a false value.

Code example

// Create strings
let str1 = "Edpresso is the best"
let str2 = "Best place to be"
let str3 = "Learn all you need"
// Check if the following prefixes exist
print(str1.hasPrefix("Edpresso"))
print(str2.hasPrefix("great"))
print(str3.hasPrefix("Learn"))

Explanation

  • Lines 2 to 4: We create some strings.
  • Lines 7 to 9: We check if the strings begin with the specified prefixes. Then, we print the results.

Free Resources