Last active
February 2, 2020 22:21
-
-
Save jakehawken/77094515ddfb93a7cdf76486459f929d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension String { | |
func removingPossibleSuffix(_ suffix: String) -> String { | |
guard hasSuffix(suffix) else { | |
return self | |
} | |
var segments = components(separatedBy: suffix) | |
if segments.count > 1 { | |
segments.removeLast() | |
return segments.joined(separator: suffix) | |
} | |
else { | |
return segments.first ?? "" | |
} | |
} | |
func removingPossibleSuffixes(_ suffixes: Set<String>) -> String { | |
guard !suffixes.isEmpty else { | |
return self | |
} | |
let suffixSubstrings = suffixes.filter { self.contains($0) } | |
guard !suffixSubstrings.isEmpty else { | |
return self | |
} | |
var output = self | |
for suffix in suffixSubstrings { | |
output = output.removingPossibleSuffix(suffix) | |
} | |
if output == self { | |
return self | |
} | |
return output.removingPossibleSuffixes(suffixSubstrings) | |
} | |
} | |
// EXAMPLES: | |
let screenName1 = "MyStupidViewController" | |
print(screenName1.removingPossibleSuffix("ViewController")) | |
// returns "MyStupid" | |
let screenName2 = "MyStupidVC" | |
print(screenName2.removingPossibleSuffix("VC")) | |
// returns "MyStupid" | |
let screenName3 = "MyStupidVC" | |
print(screenName3.removingPossibleSuffix("Fart")) | |
// returns "MyStupidVC" | |
let screenName4 = "MyStupidVCViewControllerVCViewController" | |
print(screenName4.removingPossibleSuffixes(["ViewController", "VC", "Fart"])) | |
// returns "MyStupid" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment