How Check For Prefix Or Suffix On String in Swift

By Eddy Chung

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, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts