如何计算字符串的长度?例如,我有一个定义如下的变量:

var test1: String = "Scott"

然而,我似乎找不到字符串的长度方法。


当前回答

我的两美分换雨燕3/4

如果需要有条件地编译

    #if swift(>=4.0)
            let len = text.count
        #else
            let len = text.characters.count
        #endif

其他回答

字符串和NSString是免费桥,因此您可以使用NSString和swift字符串的所有可用方法

let x = "test" as NSString
let y : NSString = "string 2"
let lenx = x.count
let leny = y.count

在Swift 4中:如果字符串不包含unicode字符,请使用以下命令

let str : String = "abcd"
let count = str.count // output 4

如果字符串包含unicode字符,请使用以下命令:

let spain = "España"
let count1 = spain.count // output 6
let count2 = spain.utf8.count // output 7

test1.endIndex给出的结果与Swift 3上的test1.characters.count相同

在swift4中,我一直使用string.count,直到今天我发现

string.endIndex.encodedOffset

是更好的替代方法,因为它更快-对于50000个字符,字符串大约比.count快6倍。.count取决于字符串长度,但.endIndex.encodedOffset不一样。

但有一个“不”。它对带有表情符号的字符串不好,它会给出错误的结果,所以只有count是正确的。

Swift 1.2更新:不再有countElement来计算集合的大小。只需使用count函数作为替换:count(“Swift”)

Swift 2.0、3.0和3.1:

let strLength=字符串字符计数

Swift 4.2(4.0以后版本):[苹果文档-字符串]

let strLength=字符串计数