iOS Swift String extensions

Sometimes we may have to dig a lot for simple operations in Swift. So from now onwards no need to worry, if anybody asks you about the following operations, you can stand in the crowd and can say, I know.

  • Get a character from a particular position in the String
  • Get a substring in between a range

Copy the below magic lines to your Swift file.

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 {
        return substringWithRange(Range(start: startIndex.advancedBy(r.startIndex), end: startIndex.advancedBy(r.endIndex)))
    }
}

Sajeel

Read more posts by this author.

Subscribe to The Magics

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!