字符串的长度作为字符串的扩展名 [英] Length of String as extension of String

查看:121
本文介绍了字符串的长度作为字符串的扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多重复的指针,但这是工作之前我更新到xcode 6.3,现在它有一个问题。



脚本:

  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))
}
}
pre>

错误:无法使用'(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 function count(). You can rename the parameter or call

var 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 with

let foo = "
                        

这篇关于字符串的长度作为字符串的扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆