Add subscript(r: Range<Int>) to String
Originator: | robnapier | ||
Number: | rdar://17158813 | Date Originated: | 04-Jun-2014 |
Status: | Open | Resolved: | |
Product: | Swift | Product Version: | |
Classification: | Reproducible: |
You should be able to slice strings by integers rather than hard-to-create StringIndexes. Here is a simple implementation: import Foundation extension String { subscript (r: Range<Int>) -> String { get { return self.substringWithRange( Range(start: advance(self.startIndex, r.startIndex), end: advance(self.startIndex, r.endIndex))) } } } var s = "Hello, playground" println(s[0 .. 5]) ==> Hello
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!
ellpisis .. ...
oops! When I suggested this "correction" above, I was not aware of the different range specifiers with .. (two dots) or ... (three dots) so, the "start + 1 is unnecessary.. Sorry.
suggestion for further improvement s[n] and s[n1..n2] and use of existing functions concatenated
extension String {
}
Evaluated in the XCode playground:
var s = "abcdefghijklmnopqrstuvwxyz"
var sub2 = s[4..12] //"efghijklm"
var c = s[5] // "f"
"abcdefgh"[2..4] // "cde"
let s2 = s.substringFrom(5, to: 24) // "fghijklmnopqrstuvwxy"
Kind Regards
Ted