Ad
Code
Diff
  • 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 = 0
    • return self.reduce("") { (string, c) in
    • guard ndx < n else {
    • ndx = 1
    • return "\(string)\(value)\(c)"
    • }
    • ndx += 1
    • return "\(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
    • }
    • }