Last active
June 25, 2017 11:47
-
-
Save bennokress/ea4aacc35cf131b7480573f57466b0f7 to your computer and use it in GitHub Desktop.
Extensions for Swift's String Type
This file contains 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 { | |
/// Usage: "Hello World".until(" World") --> "Hello" | |
mutating func until(_ string: String) { | |
var components = self.components(separatedBy: string) | |
self = components[0] | |
} | |
/// Blows a string up to totalLength by pre- and postfixing characters (e.g. "hello".withAddedDivider("-", totalLength: 13) returns "--- hello ---") | |
func withAddedDivider(_ divider: Character, totalLength: Int, padding: Int = 1) -> String { | |
let contentLength = self.count + 2 * padding | |
guard contentLength < totalLength else { return self } | |
let dividerLength = totalLength - contentLength | |
let oddLength = (totalLength - contentLength) % 2 > 0 | |
let halfDivider = String.init(repeating: divider, count: dividerLength / 2) | |
let spacing = String.init(repeating: " ", count: padding) | |
let oddLengthFix = oddLength ? "\(divider)" : "" | |
return "\(halfDivider)\(spacing)\(self)\(spacing)\(halfDivider)\(oddLengthFix)" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment