Skip to content

Instantly share code, notes, and snippets.

@hishma
Last active January 23, 2019 22:41
Show Gist options
  • Save hishma/843fd88e7ef8c1aaeae6b256223d98d5 to your computer and use it in GitHub Desktop.
Save hishma/843fd88e7ef8c1aaeae6b256223d98d5 to your computer and use it in GitHub Desktop.
String extensions to make my life more convenient. When I remember them…
extension String {
/// Replace all instances of characters in a character set.
///
/// - Parameters:
/// - characterSet: The `CharacterSet` containing the characters to replace in the string.
/// - replacementString: The `String` to replace the matched characters with.
/// - Returns: A new `String` with all characters in the character set replaced by the replacement string.
func replacingCharacters(in characterSet: CharacterSet, with replacementString: String = "") -> String {
return self.components(separatedBy: characterSet).joined(separator: replacementString)
}
/// Sparate a string by word boundaries.
///
/// - Returns: An array of strings, representing a list of words.
func words() -> [String] {
return self.substrings(options: .byWords)
}
/// Sparate a string by sentences.
///
/// - Returns: An array of strings, representing a list of sentences.
func sentences() -> [String] {
return self.substrings(options: .bySentences)
}
/// Sparate a string by paragraphs.
///
/// - Returns: An array of strings, representing a list of paragraphs.
func paragraphs() -> [String] {
return self.substrings(options: .byParagraphs)
}
/// Sparate a string by lines.
///
/// - Returns: An array of strings, representing a list of lines.
func lines() -> [String] {
return self.substrings(options: .byLines)
}
/// Sparate a string eumeration options.
///
/// - Parameter options: Options specifying types of substrings and enumeration styles. If opts is omitted or empty, body is called a single time with the range of the string specified by range.
/// - Returns: Array of strings, separated by the specified options.
func substrings(options: NSString.EnumerationOptions) -> [String] {
let range: Range<String.Index> = self.startIndex ..< self.endIndex
var substrings = [String]()
self.enumerateSubstrings(in: range, options: options) {substr,_,_,_ in
guard let substring = substr, !substring.isEmpty else { return }
substrings.append(substring)
}
return substrings
}
}
extension String: Error {}
/// Returns the string as the error description
extension String: LocalizedError {
public var errorDescription: String? { return self }
}
extension String {
/// Prepend a string to a string, you know, like amend but on the other end.
public mutating func prepend(_ other: String) {
self = other + self
}
}
extension String {
public mutating func prepend(_ other: String) {
self = other + self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment