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

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);

其他回答

这里有一些比使用全局函数更短、更自然的方法:

aString.utf16count

我不知道它是否在beta 1中可用。但它肯定在beta 2中。

只需写一个扩展就可以得到长度:

extension String {
    // MARK: Use if it's Swift 2
    func stringLength(str: String) -> Int {
        return str.characters.count
    }

    // MARK: Use if it's Swift 3
    func stringLength(_ str: String) -> Int {
        return str.characters.count
    }

    // MARK: Use if it's Swift 4
    func stringLength(_ str: String) -> Int {
        return str.count
    }
}

如果您正在寻找一种更简洁的方法来获取字符串长度,请检查这个库,它有一系列对Swift内置类的扩展http://www.dollarswift.org/#length

使用这个库,您只需执行“Some Str”.length

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

Swift 2.0、3.0和3.1:

let strLength=字符串字符计数

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

let strLength=字符串计数

您可以将此函数添加到扩展

extension NSString { 
    func charLength() -> Int {
        return count(self as String)
    }
}