Skip to content

Instantly share code, notes, and snippets.

@foxicode
Created March 3, 2020 19:11
Show Gist options
  • Select an option

  • Save foxicode/5800bbf6bba3e30eb22422f0dce4fccb to your computer and use it in GitHub Desktop.

Select an option

Save foxicode/5800bbf6bba3e30eb22422f0dce4fccb to your computer and use it in GitHub Desktop.
Swift String extension inserting separator between symbol groups
import Foundation
extension String {
mutating func insert(separator: String, every n: Int) {
self = inserting(separator: separator, every: n)
}
func inserting(separator: String, every n: Int) -> String {
var result: String = ""
let characters = Array(self)
stride(from: 0, to: count, by: n).forEach {
result += String(characters[$0..<min($0+n, count)])
if $0+n < count {
result += separator
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment