0

I padded a Swift String up to X amount of characters. Which is the most efficient way to achieve this in Swift 4.0?

Option 1

extension String {
    mutating func right_padding(padding: Int, padding_char: Character) {
        let idx = self.endIndex
        for _ in (1...padding) {
            self.insert(padding_char, at: idx)
        }
    }
}

Option 2 SO article: Padding a swift String for printing

let test = "ghost" + "\(String(repeatElement("!", count: 40)))"

Option 3

???

Option 2 seems the simplest & most efficient, but I may be missing a better way...

rustyMagnet
  • 3,479
  • 1
  • 31
  • 41
  • Note - there needs to be code to handle null strings and overly long strings but I purposely removed it. – rustyMagnet Dec 11 '17 at 09:54
  • Can you explain why the answers given in the question you linked aren't satisfactory for you. – JeremyP Dec 11 '17 at 10:16
  • I already linked that article in the original post. There are so many APIs available in Swift 4. https://oleb.net/blog/2017/11/swift-4-strings/ I wonder if there is now a better way of achieving the same padding? – rustyMagnet Dec 11 '17 at 10:20
  • 3
    I know. What's wrong with the answers that it gives? Why would they not be the answer to your question? In particular https://stackoverflow.com/a/39215372/169346 – JeremyP Dec 11 '17 at 10:22

0 Answers0