What is the hasSuffix() method in Swift?
Overview
The hasSuffix() method lets us check if a string ends with a specified string. If it is true, then true is returned. Otherwise, false is returned.
Syntax
The syntax of the hasSuffix() method is given below:
str.hasSuffix(suffix)
Parameters
suffix: This is a string, and hasSuffix() checks whether or not the str string ends with the suffix string.
Return value
The value returned is a Boolean that is true or false.
Code example
// create stringslet str1 = "Edpresso is the best"let str2 = "Best place to be"let str3 = "Learn all you need"// check the suffixes belowprint(str1.hasSuffix("Edpresso"))print(str2.hasSuffix("be"))print(str3.hasSuffix("need"))
Explanation
-
Line 2-4: We create some strings.
-
Line 7-9: We check if the strings end with specific suffixes. Then we print the results.
-
Line 7: This statement returns false because
str1does not end with “Edpresso”. -
Line 8: This statement returns true because
str2ends with “be”. -
Line 9: This statement returns true because
str3ends with “need”.