我在尝试使用Swift游乐场时,尝试了以下代码,但它并没有起作用,并告诉我'String' 没有名为 'Characters' 的成员
。我希望打印出咖啡店 中的字符数为4
。你能给我一些提示吗?谢谢。
var word = "cafe"
print("the number of characters in \(word) is \(word.characters.count)")
characters
是Swift 2中String
的一个属性,它随着Xcode 7 beta一起发布。
你可能正在使用Swift 1.2的Xcode 6.3.2版本,那么它就没有这个属性。
print("the number of characters in \(word) is \(count(word))")
Swift 2.0有两个变化:
String
不再遵循SequenceType
协议,你需要显式地访问.characters
,count()
函数已被一个"协议扩展"方法count()
所取代。println(the number of characters in \(word) is \(count(word))")
使用 Swift 2:
word.characters.count
此外,若要获取实际字符,您可调用:
let characters = Array(string)
然后,您只需调用:
let length = characters.count
然而,在Swift 1.2中,如果您不需要迭代字符或其他内容,您也可以使用计数函数:
let length = count(string)
在Swift 2中:
let length = string.count()
我想你正在阅读iBook上的Swift 2教程。这是新功能,只能在Xcode 7中使用。
word.characters.count
这样的表达式似乎有点复杂。谢谢。 - Eric Tsuiword.utf8.count
会将长度作为UTF-8字符串给出。 - Martin R