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")