How can I split the given String
in Swift into groups with given length, reading from right to left?
For example, I have string 123456789
a
Swift 4
I think the extension method is more useful.
extension String{
public func splitedBy(length: Int) -> [String] {
var result = [String]()
for i in stride(from: 0, to: self.characters.count, by: length) {
let endIndex = self.index(self.endIndex, offsetBy: -i)
let startIndex = self.index(endIndex, offsetBy: -length, limitedBy: self.startIndex) ?? self.startIndex
result.append(String(self[startIndex..
the example of use:
Swift.debugPrint("123456789".splitedBy(length: 4))
// Returned ["1", "2345", "6789"]