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

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

其他回答

我的两美分换雨燕3/4

如果需要有条件地编译

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

雨燕1.1

extension String {
    var length: Int { return countElements(self) }  // 
}

雨燕1.2

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

斯威夫特2.0

extension String {
    var length: Int { return characters.count    }  // 
}

雨燕4.2

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

let str = "Hello"
let count = str.length    // returns 5 (Int)

使用Xcode 6.4、Swift 1.2和iOS 8.4:

    //: Playground - noun: a place where people can play

    import UIKit

    var str = "  He\u{2606}  "
    count(str) // 7

    let length = count(str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())) as Int // 3
    println(length == 3) // true
var str = "Hello, playground"
var newString = str as NSString    

countElements(str)

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

countElements((newString as String))    

这将统计NSString中的字符

Swift 2.0版本:获取计数:yourString.text.characters.count

有趣的有用示例是在UITextView中显示某个数字(例如150)的字符倒计时:

func textViewDidChange(textView: UITextView) {
    yourStringLabel.text = String(150 - yourStringTextView.text.characters.count)
}