Created
May 25, 2022 04:33
-
-
Save BetterProgramming/46df73d30d073947917ac6b206163517 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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