How to write my own extension to enable Python-like String indexing?

Thank you, indeed:

let text = "hello"
print(text[slow: 0..<2]) // "he"
print(text[slow: 0...2]) // "hel"
print(text[slow: 1...]) // "ello"
print(text[slow: ..<2]) // "he"
print(text[slow: ...2]) // "hel"

extension String {
    subscript<T: RangeExpression>(slow bounds: T) -> String where T.Bound == Int {
        let range = bounds.relative(to: 0 ..< .max)
        let left = index(startIndex, offsetBy: range.lowerBound)
        let right = range.upperBound == .max ? endIndex : index(startIndex, offsetBy: range.upperBound)
        return String(self[left ..< right])
    }
}
1 Like