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

var test1: String = "Scott"

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


当前回答

在Swift 4.1和Xcode 9.4.1中

在Objective c和Swift中获取长度是不同的。在Obj-c中我们使用长度属性,但在Swift中我们使用计数属性

例子:

//In Swift
let stringLenght = "This is my String"
print(stringLenght.count)

//In Objective c
NSString * stringLenght = @"This is my String";
NSLog(@"%lu", stringLenght.length);

其他回答

你可以这样试试

var test1: String = "Scott"
var length =  test1.bridgeToObjectiveC().length

在Swift 4.1和Xcode 9.4.1中

在Objective c和Swift中获取长度是不同的。在Obj-c中我们使用长度属性,但在Swift中我们使用计数属性

例子:

//In Swift
let stringLenght = "This is my String"
print(stringLenght.count)

//In Objective c
NSString * stringLenght = @"This is my String";
NSLog(@"%lu", stringLenght.length);
var str = "Hello, playground"
var newString = str as NSString    

countElements(str)

这将统计正则Swift字符串中的字符

countElements((newString as String))    

这将统计NSString中的字符

在Xcode 6.1.1中

extension String {    
    var length : Int { return self.utf16Count  }
}

我认为脑力劳动者会在每一个次要版本上改变这一点。

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

Swift 2.0、3.0和3.1:

let strLength=字符串字符计数

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

let strLength=字符串计数