String extension for range of characters/character at nth position

String extension for range of characters/character at nth position

I spotted this extension somewhere online a while ago (kjmcneish?) that can come in pretty handy.

extension String {
    
    // Returns a range of characters (e.g. s[0...3])
    subscript (r: Range<Int>) -> String {
        let start = advance(self.startIndex, r.startIndex)
        let end = advance(self.startIndex, r.endIndex)
        return substringWithRange(Range(start: start, end: end))
    }
    
    // Returns the nth character (e.g. s[1])
    subscript (i: Int) -> String {
        
        return self[i...i]
    }
}

Usage:

let e = "On my ship, the Rocinante, Wheeling through the galaxies."
let e1 = e[0...1]  // Returns a range of characters ("On")
let e2 = e[3]  //Returns a single character ("m")

 

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.