Last active
June 1, 2020 02:16
-
-
Save darhonbek/3b8d9254ea1888942744d790e77358ab to your computer and use it in GitHub Desktop.
String Indexation in Swift
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 StringProtocol { | |
subscript(_ offset: Int) -> Element { | |
return self[index(startIndex, offsetBy: offset)] | |
} | |
subscript(_ range: Range<Int>) -> SubSequence { | |
return prefix(range.lowerBound+range.count).suffix(range.count) | |
} | |
subscript(_ range: ClosedRange<Int>) -> SubSequence { | |
return prefix(range.lowerBound+range.count).suffix(range.count) | |
} | |
subscript(_ range: PartialRangeThrough<Int>) -> SubSequence { | |
return prefix(range.upperBound.advanced(by: 1)) | |
} | |
subscript(_ range: PartialRangeUpTo<Int>) -> SubSequence { | |
return prefix(range.upperBound) | |
} | |
subscript(_ range: PartialRangeFrom<Int>) -> SubSequence { | |
return suffix(Swift.max(0, count-range.lowerBound)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment