Created
March 3, 2020 19:11
-
-
Save foxicode/5800bbf6bba3e30eb22422f0dce4fccb to your computer and use it in GitHub Desktop.
Swift String extension inserting separator between symbol groups
This file contains hidden or 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
| 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