Skip to content

Instantly share code, notes, and snippets.

@shmidt
Created August 28, 2022 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shmidt/58b13ada07a921c1ebb9d2af70c92fcc to your computer and use it in GitHub Desktop.
Save shmidt/58b13ada07a921c1ebb9d2af70c92fcc to your computer and use it in GitHub Desktop.
StringExtension.swift
// https://stackoverflow.com/a/56763580/592035
extension String {
subscript(_ i: Int) -> String {
let idx1 = index(startIndex, offsetBy: i)
let idx2 = index(idx1, offsetBy: 1)
return String(self[idx1..<idx2])
}
subscript (r: Range<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(startIndex, offsetBy: r.upperBound)
return String(self[start ..< end])
}
subscript (r: CountableClosedRange<Int>) -> String {
let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.index(startIndex, offsetBy: r.upperBound - r.lowerBound)
return String(self[startIndex...endIndex])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment