Skip to content

Instantly share code, notes, and snippets.

@ilyannn
Forked from erica/indents.swift
Last active November 24, 2015 19:05
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 ilyannn/b0b9860c463a1013fc95 to your computer and use it in GitHub Desktop.
Save ilyannn/b0b9860c463a1013fc95 to your computer and use it in GitHub Desktop.
enum StringPaddingStyle {
case Left, Right
}
func padString(source: String,
with character: Character = " ",
fill target: Int,
style: StringPaddingStyle = .Left
) -> String {
let count = max(target - source.characters.count, 0)
let insert = String(count: count, repeatedValue: character)
return style == .Left
? insert + source
: source + insert
}
enum StringPaddingStyle {
case Left, Right, Center
}
extension String {
func padded(with character: Character = " ",
to target: Int,
style: StringPaddingStyle = .Left
) -> String {
let total = max(target - characters.count, 0)
let left: Int
switch style {
case .Left: left = 0
case .Right: left = total
case .Center: left = total / 2
}
let 🔨 = { String(count: $0, repeatedValue: character) }
return 🔨(left) + self + 🔨(total - left)
}
}
"string".padded(with: "_", to: 10, style: .Center)
"another".padded(to: 15)
enum StringPaddingStyle {
case Left, Right, Center
}
func *(style: StringPaddingStyle, length: Int) -> Int {
switch style {
case .Left: return 0
case .Right: return length
case .Center: return length / 2
}
}
extension String {
func padded(with character: Character = " ",
to target: Int,
style: StringPaddingStyle = .Left
) -> String {
let 🔨 = { String(count: $0, repeatedValue: character) }
let total = max(target - characters.count, 0)
let left = style * total
let right = total - left
return 🔨(left) + self + 🔨(right)
}
}
"string".padded(with: "_", to: 10, style: .Center)
"another".padded(to: 15)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment