Swift String Substring Retrieval

Posted 03/30/2016 2:23 PM by Corey Klass

Swift supports some pretty cool subscript operations, particularly in for loops. But what about String manipulation? Extensions to the rescue!

Here you can find a Swift extension that lets you specify ranges when working with String objects to obtain substrings:

    let string1 = "ABCDE"
    let string2 = string1[0...3] // returns "ABCD"
    let string3 = string1[1..<4] // returns "BCD"

These are valid String objects that can be used as you would any other String.

    //  String+CKTextManipulation.swift

    import Foundation

    extension String {

        subscript (i: Int) -> Character {
            return self[self.startIndex.advancedBy(i)]

        subscript (i: Int) -> String {
            return String(self[i] as Character)

        subscript (r: Range<Int>) -> String {
            let start = self.startIndex.advancedBy(r.startIndex)
            let end = self.start.advancedBy(r.endIndex - r.startIndex)

            return self[start..<end]