Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Created November 17, 2015 08:36
Show Gist options
  • Save IanKeen/429bf37d6335b64e03da to your computer and use it in GitHub Desktop.
Save IanKeen/429bf37d6335b64e03da to your computer and use it in GitHub Desktop.
String extension to allow splitting a string by multiple components/tokens
extension String {
func componentsSeparatedByStrings(separators: [String]) -> [String] {
return separators.reduce([self]) { result, separator in
return result.flatMap { $0.componentsSeparatedByString(separator) }
}
.map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) }
}
}
/* Usage */
"hello.there/how?are!you".componentsSeparatedByStrings([".", "/", "?", "!"])
/* Result: ["hello", "there", "how", "are", "you"] */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment