Swift String hasPrefix()

The hasPrefix() method checks whether the string begins with the specified string or not.

Example

var str = "Kathmandu"

// checks if "Kathmandu" starts with "Kath" print(str.hasPrefix("Kath"))
// Output: true

hasPrefix() Syntax

The syntax of the string hasPrefix() method is:

string.hasPrefix(str: String)

Here, string is an object of the String class.


hasPrefix() Parameters

The hasPrefix() method takes a single parameter:

  1. str - check whether string starts with str or not

hasPrefix() Return Value

The hasPrefix() method returns:

  1. true - if the string begins with the given string
  2. false - if the string doesn't begin with the given string

Note: The hasPrefix() method is case-sensitive.


Example 1: Swift string hasPrefix()

var str = "Swift Programming"

print(str.hasPrefix("Swift")) // true
print(str.hasPrefix("S")) // true
print(str.hasPrefix("Swift Program")) // true

print(str.hasPrefix("swift")) // false
print(str.hasPrefix("wif")) // false

Output

true
true
true
false
false

Example 2: Using hasPrefix() With if...else

var song = "For the good times"

// true because song has "For the" prefix if(song.hasPrefix("For the")) {
print ("Penned by Kris") } else { print ("Some Other song ") }
// false because song doesn't have "Good time" prefix if(song.hasPrefix("Good times")){
print ("Penned by Bernard") } else{ print ("Some other artist ") }

Output

Penned by Kris
Some other artist