Skip to content

Instantly share code, notes, and snippets.

@commscheck
Last active November 22, 2018 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save commscheck/c9de0924c2dd8f6c96ad884eda0c04d9 to your computer and use it in GitHub Desktop.
Save commscheck/c9de0924c2dd8f6c96ad884eda0c04d9 to your computer and use it in GitHub Desktop.
Pad list of strings
extension Collection where Element == String {
func pad(to commonString: String) -> [String] {
let stringsAndWidths = self.map { string -> (String, Int) in
return (string, string[string.startIndex ..< string.range(of: commonString)!.lowerBound].count)
}
let marginWidth = stringsAndWidths.map { $0.1 }.reduce(0) { result, count -> Int in Swift.max(result, count) }
return stringsAndWidths.map { tuple -> String in
let (string, width) = tuple
return string.prefix(width).padding(toLength: marginWidth, withPad: " ", startingAt: 0) + tuple.0.suffix(tuple.0.count - tuple.1)
}
}
}
let input = """
func foo() { return NSLocalizedString("foo", comment: "this is foo") }
func alphaBetaCharlie() { return NSLocalizedString("alpha beta charlie", comment: "this is alpha beta charlie") }
func alpha() { return NSLocalizedString("alpha", comment: "this is alpha") }
"""
let strings = input.split(separator: "\n").map { String($0) }
let fixed = strings
.pad(to: "{ return NSLocalizedString")
.pad(to: "comment: ")
for string in fixed {
print(string)
}
// Output:
//
// func foo() { return NSLocalizedString("foo", comment: "this is foo") }
// func alphaBetaCharlie() { return NSLocalizedString("alpha beta charlie", comment: "this is alpha beta charlie") }
// func alpha() { return NSLocalizedString("alpha", comment: "this is alpha") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment