遍历String Swift 2.0 [英] Iterate through a String Swift 2.0
问题描述
我正在尝试在Swift操场上编写一段非常简单的代码.
I am trying to do a very simple piece of code in Swift playgrounds.
var word = "Zebra"
for i in word {
print(i)
}
但是,我总是在第3行出现错误.
However, I always get an error on line 3.
字符串"没有名为生成器"的成员
'String' does not have a member named 'Generator'
关于这为什么不起作用的任何想法?注意:我正在使用带有Swift 2.0的Xcode 7(字符串和字符).
Any ideas on why this doesn't work? Note: I am working in Xcode 7, with Swift 2.0 (Strings and Characters).
推荐答案
从Swift 2开始,String
不符合SequenceType
.但是,可以在String
上使用characters
属性. characters
返回
As of Swift 2, String
doesn't conform to SequenceType
. However, you can use the characters
property on String
. characters
returns a String.CharacterView
which conforms to SequenceType
and so can be iterated through with a for
loop:
let word = "Zebra"
for i in word.characters {
print(i)
}
或者,您可以在String
上添加扩展名以使其符合SequenceType
:
Alternatively, you could add an extension to String
to make it conform to SequenceType
:
extension String: SequenceType {}
// Now you can use String in for loop again.
for i in "Zebra" {
print(i)
}
尽管如此,但我确定Apple有理由删除String
与SequenceType
的一致性,因此第一种选择似乎是更好的选择.探索有趣的事情是很有趣的.
Although, I'm sure Apple had a reason for removing String
's conformance to SequenceType
and so the first option seems like the better choice. It's interesting to explore what's possible though.
这篇关于遍历String Swift 2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!