Swift – Check if String Ends with Another String
To check if a String str1
ends with another String str2
in Swift, use String.hasSuffix()
function. Call hasSuffix() function on str1
and pass str2
as argument.
The syntax to check if String str1
ends with the String str2
is
str1.hasSuffix(str2)
hasSuffix()
function returns a boolean value. If string str1
ends with the string str2
, then the function returns true
, else the function returns false
.
Note: Make sure to import Foundation in your swift program.
Example
In this example, we will take two string in variables str1 and str2. Using String.hasSuffix() function, we will check if the string str1 ends with the string str2.
main.swift
import Foundation
var str1 = "Hello World"
var str2 = "rld"
var result = str1.hasSuffix(str2)
print("Does str1 end with str2 : \(result)")
Output
Does str1 end with str2 : true
Now, we will take different values for str1 and str2, such that str1 does not end with str2, and check the result of hasSuffix() function.
main.swift
import Foundation
var str1 = "Hello World"
var str2 = "Wor"
var result = str1.hasSuffix(str2)
print("Does str1 end with str2 : \(result)")
Output
Does str1 end with str2 : false
Conclusion
In this Swift Tutorial, we learned how to check if a string ends with another specific string using String.hasSuffix() function.