Ad
Code
Diff
  • extension String {
        func insert(_ value: String, interval: Int) -> String {
            guard interval > 0 && interval < count else { return self }
            var result = ""
            for (index, char) in self.enumerated() {
                result += String(char)
                if (index + 1) % interval == 0 && index + 1 != count {
                    result += value
                }
            }
            return result
        }
    }
    
    • extension String {
    • func insert(_ value: String, interval: Int) -> String {
    • guard interval > 0 && interval < self.count else { return self }
    • let substrings: [Substring] = stride(from: 0, to: self.count, by: interval).map { index in
    • let startIndex = self.index(self.startIndex, offsetBy: index)
    • let endIndex = self.index(startIndex, offsetBy: interval, limitedBy: self.endIndex) ?? self.endIndex
    • return self[startIndex..<endIndex]
    • }
    • return substrings.joined(separator: value)
    • }
    • func insert(_ value: String, interval: Int) -> String {
    • guard interval > 0 && interval < count else { return self }
    • var result = ""
    • for (index, char) in self.enumerated() {
    • result += String(char)
    • if (index + 1) % interval == 0 && index + 1 != count {
    • result += value
    • }
    • }
    • return result
    • }
    • }