Skip to content

Instantly share code, notes, and snippets.

@JacopoMangiavacchi
Last active November 28, 2017 06:35
Show Gist options
  • Save JacopoMangiavacchi/b918515412ba441c0277d3d06fbb82ad to your computer and use it in GitHub Desktop.
Save JacopoMangiavacchi/b918515412ba441c0277d3d06fbb82ad to your computer and use it in GitHub Desktop.
import Foundation
extension String {
subscript(value: PartialRangeUpTo<Int>) -> Substring {
get {
return self[..<index(startIndex, offsetBy: value.upperBound)]
}
}
subscript(value: PartialRangeThrough<Int>) -> Substring {
get {
return self[...index(startIndex, offsetBy: value.upperBound)]
}
}
subscript(value: PartialRangeFrom<Int>) -> Substring {
get {
return self[index(startIndex, offsetBy: value.lowerBound)...]
}
}
subscript(value: CountableRange<Int>) -> Substring {
get {
return self[index(startIndex, offsetBy: value.lowerBound)..<index(startIndex, offsetBy: value.upperBound)]
}
}
subscript(value: CountableClosedRange<Int>) -> Substring {
get {
return self[index(startIndex, offsetBy: value.lowerBound)...index(startIndex, offsetBy: value.upperBound)]
}
}
subscript(value: Int) -> Substring {
get {
return self[index(startIndex, offsetBy: value)..<index(startIndex, offsetBy: value+1)]
}
}
}
// let text = "Hello world"
// text[...4] // "Hello"
// text[5] // " "
// text[6...] // "world"
// text[3...] // "lo world"
// text[3..<7] // "lo w"
// text[3...7] // "lo wo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment