Checking for prefixes or suffixes is a common operation for strings.
Let’s go over how you can do this easily in Swift.
To check for a prefix in Swift, simply use the hasPrefix
function.
let str = "prefix-string"
if str.hasPrefix("prefix") {
print("has prefix")
}
If you’d like to get the prefix or the first n characters of a string, use the prefix
function.
let str = "prefix-string"
print(str.prefix(6))
This will print prefix
.
To check for a suffix in Swift, simply use the hasSuffix
function.
let str = "string-suffix"
if str.hasSuffix("suffix") { // true
print("has suffix")
}
If you’d like to get the prefix or the last n characters of a string, use the suffix
function.
let str = "string-suffix"
print(str.suffix(6))
This will print suffix
.
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.