Search code examples
iosswiftswift-extensions

Complicated Swift Extension


I want to create an extension for the String class in Swift that allows you to get a substring via the subscript operator like in Python. This can be accomplished with the Range class in the following way

extension String {

    subscript (range: Range<Int>) -> String? {
        if range.startIndex < 0 || range.endIndex > count(self) {
            return nil
        }
        let range = Range(start: advance(startIndex, range.startIndex), end: advance(startIndex, range.endIndex))
        return substringWithRange(range)
    }
}

This enables the following usage

let string = "OptimusPrime"
string[0...6] // "Optimus"

However, I want to be able to index the string from the end as well as the beginning using negative integers.

string[7...(-1)] // "Prim"

Since the Range class doesn't allow startIndex to be greater than endIndex the extension above is not sufficient to achieve this behavior.

Since Range objects apparently can't be used for this extension, it makes sense to me to simply use the same syntax as in Python

string[0:2] // "Op"
string[0:-1] // "OptimusPrim"

Is this possible? How would I go about doing this?


Solution

  • i think you could get python-like syntax like this:

    subscript (start:Int, end:Int) -> String?
    

    which would let you go "bla bla"[0,3]

    then if you take a negative number in, just make convert it to the string length minus the negative number instead so the range is valid