Matching Swift Strings by Prefix or Suffix
Last Run on XCODE 11.4 / Swift 5.2
A simple way to check if a string starts or ends with a certain pattern is to use the method hasSuffix
and hasPrefix
available to Strings.
In the code snippet below, we will check if a string begins or ends with a specific text pattern.
let fileName1 = "InstagramCover.jpg"
let fileName2 = "SnapchatCover.doc"
fileName1.hasSuffix("jpg") // result --> True
fileName2.hasSuffix("jpg") // result --> False
fileName1.hasPrefix("Instagram") // --> True
fileName2.hasPrefix("Facebook") // result --> False
If we need to check against multiple variations, we can’t just use hasSuffix
. Instead, we will have
to use it along with another method contains
. Checkout the code snippet below.
let fileName1 = "InstagramCover.png"
let fileName2 = "SnapchatCover.doc"
let fileExtensions = ["jpg", "jpeg", "png"]
let socialMediaNameFilePrefixes = ["Instagram", "Facebook", "Twitter"]
fileExtensions.contains(where: fileName1.hasSuffix) // result --> True
fileExtensions.contains(where: fileName2.hasSuffix) // result --> False
socialMediaNameFilePrefixes.contains(where: fileName1.hasPrefix) // result --> True
socialMediaNameFilePrefixes.contains(where: fileName2.hasPrefix) // result --> False