I am attempting to rewrite this Objective C method that has similar functionality to Python's lstrip
(which removes characters from the LH of a string) and rstrip
(strips the RH of a string of characters).
The lstrip
version works great:
// this works
func lstrip(st_in: String,
trimSet: NSCharacterSet=NSCharacterSet.whitespaceAndNewlineCharacterSet())-> String {
let wanted=trimSet.invertedSet
if let r=st_in.rangeOfCharacterFromSet(wanted) {
return st_in.substringFromIndex(r.startIndex)
}
return ""
}
I am having trouble with the rstrip
version however.
This is what I have:
// does not compile
func rstrip(st_in: String,
trimSet: NSCharacterSet=NSCharacterSet.whitespaceAndNewlineCharacterSet())-> String {
let wanted=trimSet.invertedSet
let tgt=String(st_in.characters.reverse())
if let r=tgt.rangeOfCharacterFromSet(wanted) {
// st_in.characters.count - r.startIndex
return st_in.substringToIndex(st_in.startIndex.advancedBy((st_in.characters.count as Int) - (r.startIndex as Int)))
}
return ""
}
Issues:
- The Swift version of
.rangeOfCharacterFromSet
does not seem to supportoptions:NSBackwardsSearch
-- I use forward search onst_in.characters.reverse()
which seems to work; - The major issue (and my question is)
st_in.substringToIndex(st_in.startIndex.advancedBy((st_in.characters.count as Int) - (r.startIndex as Int)))
does not compile. I can see in the debugger that the values are correct, butr.startIndex
is typeIndex
and I cannot use that value directly for arithmetic nor can I coerce that to an Int value nor can I access the value I see in it.
So given this in the debugger:
56> st
$R33: String = " \t\n I needz trimin'¡ \t\n\n\n\n"
57> String(st.characters.reverse())
$R34: String = "\n\n\n\n\t ¡'nimirt zdeen I \n\t "
58> String(st.characters.reverse()).rangeOfCharacterFromSet(trimSet.invertedSet)!.startIndex
$R35: Index = {
_base = {
_position = 9
_core = {
_baseAddress = 0x0000000101207ee0
_countAndFlags = 9223372036854775839
_owner = Some {
instance_type = 0x0000000101207ec0
}
}
}
_lengthUTF16 = 1
}
You can see that _position=9
in the Index structure -- just what I need in st_in.substringToIndex(st_in.startIndex.advancedBy(st_in.characters.count - r.startIndex))
but I do not know how to access it in Swift.
Ideas?