字符串的长度作为字符串的扩展名 [英] Length of String as extension of String
问题描述
我知道有很多重复的指针,但这是工作之前我更新到xcode 6.3,现在它有一个问题。
脚本:
extension String {
pre>
func removeCharsFromEnd(count:Int) - > String {
var getSelf = self as String
var stringLength = count(getSelf.utf16)
let substringIndex =(stringLength< count)? 0:stringLength - count
return self.substringToIndex(advance(self.startIndex,substringIndex))
}
}
错误:无法使用'(String.UTF16View)类型的列表的参数调用'count'
< hr>
我还要指出,这种新的计数方法在我已经使用过的其他地方(在这个扩展之外)。
提前感谢。
解决方案
count
的扩展方法参数,并隐藏
Swift库函数count()
。您可以重命名参数
或调用var stringLength = Swift.count(getSelf.utf16)
但是请注意,计算UTF的数量-16代码单位在这里是错误的,应该是
var stringLength = Swift.count(getSelf)
来计算字符串中的字符数,因为这是
advance
也计数。您可以轻松验证let foo =
I know that there will be lots of pointers to duplicates but this worked before I updated to xcode 6.3 and now it has a problem with it.
The script:
extension String { func removeCharsFromEnd(count:Int) -> String { var getSelf = self as String var stringLength = count(getSelf.utf16) let substringIndex = (stringLength < count) ? 0 : stringLength - count return self.substringToIndex(advance(self.startIndex, substringIndex)) } }
Error : Cannot invoke 'count' with an argument of list of type '(String.UTF16View)'
I also want to point out that this new method for counting works everywhere else I have used out (outside of this extension).
Thanks in advance.
解决方案
count
is the name of your extension method parameter and hides the Swift library functioncount()
. You can rename the parameter or callvar stringLength = Swift.count(getSelf.utf16)
explicitly.
But note that counting the number of UTF-16 code units is wrong here, it should be
var stringLength = Swift.count(getSelf)
to count the number of characters in the string, because that is what
advance()
also counts. You can verify that easily withlet foo = "
这篇关于字符串的长度作为字符串的扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!