Subscripting in String extension to access substrings and characters with Int types

  1. I'm understand the problem with Character and the use of Collection of these.
  2. Be honest: people is doing terrible things in code to solve this problem because to work with String.Index is a headache.
  3. We need a REAL solution, and we need that language will implement the best possible solution and more efficient directly for use of any developer.
  4. The best solution is to extend the String with a pure Swift implementation, better than anyone can do it. The best possible solution using Swift with the tools we've got today.

This is my solution:

extension String {    
    private func nearestIndex(pos:Int) -> String.Index {
        if pos >= count {
            return index(before: endIndex)
        }
        if pos <= 0 {
            return startIndex
        }
        if pos < (count / 2) {
            return index(startIndex, offsetBy: pos)
        } else {
            return index(endIndex, offsetBy: -(count-pos))
        }
    }
    
    subscript (range:ClosedRange) -> Substring {
        return self[nearestIndex(pos: range.lowerBound)...nearestIndex(pos: range.upperBound)]
    }
    
    subscript (range:Range) -> Substring {
        return self[nearestIndex(pos: range.lowerBound)..<nearestIndex(pos: range.upperBound)]
    }
    
    subscript (range:PartialRangeFrom) -> Substring {
        return self[nearestIndex(pos: range.lowerBound)...index(before: endIndex)]
    }
    
    subscript (range:PartialRangeUpTo) -> Substring {
        return self[startIndex..<nearestIndex(pos: range.upperBound)]
    }
    
    subscript (range:PartialRangeThrough) -> Substring {
        return self[startIndex...nearestIndex(pos: range.upperBound)]
    }
}

I think it's elegant and the best you can do with the actual problem. I think the language must provide the best solution for each problem, and not a complex answer that not help to fix the problem, making the people uses a worse solution.

let cadena = "A long time ago in a galaxy far far away"

cadena.count

cadena[5...25]

cadena[5...250]

cadena[-5..<25]

cadena[1...41]

cadena[...30]

cadena[10...]

cadena[..<30]

This is the way I see it: a developer uses an inefficient way with a bad function (offsetBy). We can give us the best possible solution at this point, made in Swift itself.

Thanks in advance

1 Like