How Check For Prefix Or Suffix On String in Swift

Checking for prefixes or suffixes is a common operation for strings.

Let’s go over how you can do this easily in Swift.

Checking For Prefixes

To check for a prefix in Swift, simply use the hasPrefix function.

let str = "prefix-string"
if str.hasPrefix("prefix") {
    print("has prefix")
}

How To Get Prefix Of String

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.

Checking For Suffixes

To check for a suffix in Swift, simply use the hasSuffix function.

let str = "string-suffix"
if str.hasSuffix("suffix") { // true
    print("has suffix")
}

How To Get Suffix Of String

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.

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts