Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

suffix
string
swift
communitycreator

What is the hasSuffix() method in Swift?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 strings
let str1 = "Edpresso is the best"
let str2 = "Best place to be"
let str3 = "Learn all you need"
// check the suffixes below
print(str1.hasSuffix("Edpresso"))
print(str2.hasSuffix("be"))
print(str3.hasSuffix("need"))
Check if a string ends with a certain suffix in Swift

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 str1 does not end with “Edpresso”.

  • Line 8: This statement returns true because str2 ends with “be”.

  • Line 9: This statement returns true because str3 ends with “need”.

RELATED TAGS

suffix
string
swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring