Ad
Code
Diff
  • 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)
    	}
    }
    
    • 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
    • }
    • 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)
    • }
    • }