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

var test1: String = "Scott"

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


当前回答

在Swift 2.x中,以下是如何找到字符串的长度

let findLength = "This is a string of text"
findLength.characters.count

返回24

其他回答

在Swift中计算字符串的最佳方法是:

var str = "Hello World"
var length = count(str.utf16)

在Swift 2.x中,以下是如何找到字符串的长度

let findLength = "This is a string of text"
findLength.characters.count

返回24

斯威夫特4

let str =  "Your name"

str.count 

记住:空格也计入数字

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

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

func textViewDidChange(textView: UITextView) {
    yourStringLabel.text = String(150 - yourStringTextView.text.characters.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