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

var test1: String = "Scott"

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


当前回答

您可以使用SwiftString(https://github.com/amayne/SwiftString)这样做。

“string”.length//6

免责声明:我写了这个扩展

其他回答

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

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

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

这是我最后做的

let replacementTextAsDecimal = Double(string)

if string.characters.count > 0 &&
    replacementTextAsDecimal == nil &&
    replacementTextHasDecimalSeparator == nil {
        return false
}

Swift 5.0字符串可以被视为单个字符的数组。因此,要返回字符串的长度,可以使用string.count来计算字符数组中的项数。

在Xcode 6.1.1中

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

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