Swift 5+:
(迅捷5+:)
test1.count
(Swift 5.0 strings can, in some ways, simply be treated as an array. Hence you can use .count
or for example .first
)
((在某些方面,Swift 5.0字符串可以简单地视为一个数组。因此,您可以使用.count
或例如.first
))
As of Swift 4
(从Swift 4开始)
It's just:
(只是:)
test1.count
for reasons.
(原因。)
(Thanks to Martin R)
((感谢Martin R))
As of Swift 2:
(从Swift 2开始:)
With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol.
(在Swift 2中,Apple已将全局功能更改为协议扩展,这些扩展可与符合协议的任何类型匹配。)
Thus the new syntax is: (因此,新语法为:)
test1.characters.count
(Thanks to JohnDifool for the heads up)
((感谢JohnDifool的注意))
As of Swift 1
(从Swift 1开始)
Use the count characters method:
(使用计数字符方法:)
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
println("unusualMenagerie has (count(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"
right from the Apple Swift Guide
(直接来自Apple Swift指南)
(note, for versions of Swift earlier than 1.2, this would be countElements(unusualMenagerie)
instead)
((请注意,对于早于1.2的Swift版本,它将countElements(unusualMenagerie)
))
for your variable, it would be
(对于您的变量,它将是)
length = count(test1) // was countElements in earlier versions of Swift
Or you can use test1.utf16count
(或者您可以使用test1.utf16count)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…