Skip to content

Instantly share code, notes, and snippets.

@MemoryReload
Forked from BetterProgramming/String.swift
Created June 17, 2022 10:34
Show Gist options
  • Save MemoryReload/b0de2f5b12e23b00ce01486b9a6cfc2f to your computer and use it in GitHub Desktop.
Save MemoryReload/b0de2f5b12e23b00ce01486b9a6cfc2f to your computer and use it in GitHub Desktop.
extension String {
var length: Int {
return count
}
subscript (i: Int) -> String {
return self[i ..< i + 1]
}
func substring(fromIndex: Int) -> String {
return self[min(fromIndex, length) ..< length]
}
func substring(toIndex: Int) -> String {
return self[0 ..< max(0, toIndex)]
}
subscript (r: Range<Int>) -> String {
let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
upper: min(length, max(0, r.upperBound))))
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(start, offsetBy: range.upperBound - range.lowerBound)
return String(self[start ..< end])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment