Negative Slicing and Indexing of Strings in Swift

I ran across this SO post regarding indexing and slicing Strings in Swift, and I added some negative indexing and slicing functionality to the extension.

import Foundation

extension String {
    subscript(integerIndex: Int) -> Character {
        let index: Index
        if integerIndex >= 0 {
            index = startIndex.advancedBy(integerIndex)
        } else {
            index = startIndex.advancedBy(characters.count+integerIndex)
        }
        return self[index]
    }
    subscript(integerRange: Range<Int>) -> String {
        let start: Index
        let end: Index
        if integerRange.startIndex >= 0 {
            start = startIndex.advancedBy(integerRange.startIndex)
            end   = startIndex.advancedBy(integerRange.endIndex)
        } else {
            start = startIndex.advancedBy(characters.count+integerRange.startIndex)
            end   = startIndex.advancedBy(characters.count+integerRange.endIndex)
        }
        let range: Range = start..<end
        return self[range]
    }
}

var s = "Hallo"
s[0]+s[-1]        // "Ho"
s[0...2]          // "Hal"
s[0...2]+s[1...2] // "Halal"
s[-2 ... -1]      // "lo"

Leave a Reply

Your email address will not be published. Required fields are marked *