ios - Length of String as extension of String -
i know there lots of pointers duplicates worked before updated xcode 6.3 , has problem it.
the script:
extension string { func removecharsfromend(count:int) -> string { var getself = self string var stringlength = count(getself.utf16) let substringindex = (stringlength < count) ? 0 : stringlength - count return self.substringtoindex(advance(self.startindex, substringindex)) } }
error : cannot invoke 'count' argument of list of type '(string.utf16view)'
i want point out new method counting works everywhere else have used out (outside of extension).
thanks in advance.
count
name of extension method parameter , hides swift library function count()
. can rename parameter or call
var stringlength = swift.count(getself.utf16)
explicitly.
but note counting number of utf-16 code units wrong here, should
var stringlength = swift.count(getself)
to count number of characters in string, because advance()
counts. can verify with
let foo = "😀😁😂".removecharsfromend(1) println(foo)
here simplified version of method:
extension string { func removecharsfromend(count : int) -> string { precondition(count >= 0, "attempt call removecharsfromend() negative count") // decrement `endindex` `count`, not beyond `startindex`: let idx = advance(self.endindex, -count, self.startindex) return self.substringtoindex(idx) } }
using three-argument version of advance()
negative distance.
update swift 2/xcode 7:
extension string { func removecharsfromend(count : int) -> string { precondition(count >= 0, "attempt call removecharsfromend() negative count") // decrement `endindex` `count`, not beyond `startindex`: let idx = self.endindex.advancedby(-count, limit: self.startindex) return self.substringtoindex(idx) } }