Swift 1.2和Swift 2.0中的字符串长度 [英] String length in Swift 1.2 and Swift 2.0

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

问题描述

在Swift的早期版本中,我有以下代码。

In the previous version of Swift, I had the following code.

func myfunc(mystr: String) {
    if mystr.utf16Count >= 3 {

使用最新版本的Swift 1.2,我现在得到以下错误。

With the latest release of Swift 1.2, I now get the following error.

'utf16Count' is unavailable: Take the count of a UTF-16 view instead, i.e. count(str.utf16)

好的,所以我按如下方式更改了我的代码。

Ok, so I change my code as follows.

func myfunc(mystr: String) {
    if count(mystr.utf16) >= 3 {

但这不起作用。我现在收到以下错误消息。

But that doesn't work. I now get the following error message instead.

'(String.UTF16View) -> _' is not identical to 'Int16'

获取字符串长度的正确方法是什么使用Swift 1.2?

What is the correct way to get the length of a string with Swift 1.2?

推荐答案

您可以使用扩展名:

extension String {
     var length: Int { return count(self)         }  // Swift 1.2
}

你可以使用它:

if mystr.length >= 3 {

}

或者你可以直接算这个方式:

Or you can directly count this way:

if count(mystr) >= 3{

}

这对我也有用:

if count(mystr.utf16) >= 3 {

}

对于 Swift 2.0:

extension String {
    var length: Int {
        return characters.count
    }
}
let str = "Hello, World"
str.length  //12

另一个分机:

extension String {
    var length: Int {
        return (self as NSString).length
    }
}
let str = "Hello, World"
str.length //12

如果你想直接使用:

let str: String = "Hello, World"
print(str.characters.count) // 12

let str1: String = "Hello, World"
print(str1.endIndex) // 12

let str2 = "Hello, World"
NSString(string: str2).length  //12

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

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