extension String { func insert(_ value: String, n: Int) -> String { guard n > 0 else { return self } var result: String = "" stride(from: 0, to: self.count, by: n).forEach { i in let startIndex = self.index(self.startIndex, offsetBy: i) let endIndex = self.index(startIndex, offsetBy: n, limitedBy: self.endIndex) ?? self.endIndex result += (result.isEmpty ? "" : value) + self[startIndex..<endIndex] } return result } }
- extension String {
- func insert(_ value: String, n: Int) -> String {
guard n > 0 else {return self}var ndx = 0return self.reduce("") { (string, c) inguard ndx < n else {ndx = 1return "\(string)\(value)\(c)"}ndx += 1return "\(string)\(c)"- guard n > 0 else { return self }
- var result: String = ""
- stride(from: 0, to: self.count, by: n).forEach { i in
- let startIndex = self.index(self.startIndex, offsetBy: i)
- let endIndex = self.index(startIndex, offsetBy: n, limitedBy: self.endIndex) ?? self.endIndex
- result += (result.isEmpty ? "" : value) + self[startIndex..<endIndex]
- }
- return result
- }
- }