Swift String hasSuffix()

The hasSuffix() method checks whether the string ends with the specified string or not.

Example

var str = "Kathmandu"

// checks if "Kathmandu" ends with "ndu" print(str.hasSuffix("ndu"))
// Output: true

hasSuffix() Syntax

The syntax of the string hasSuffix() method is:

string.hasSuffix(str: String)

Here, string is an object of the String class.


hasSuffix() Parameters

The hasSuffix() method takes a single parameter:

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

hasSuffix() Return Value

The hasSuffix() method returns:

  1. true - if the string ends with the given string
  2. false - if the string doesn't end with the given string

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


Example 1: Swift string hasSuffix()

var str = "Swift Programming"

print(str.hasSuffix("ing")) // true
print(str.hasSuffix("g")) // true
print(str.hasSuffix("Programming")) // true

print(str.hasSuffix("programming")) // false
print(str.hasSuffix("min")) // false

Output

true
true
true
false
false

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

var song = "For the good times"

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

Output

Penned by Kris
Some other artist
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges