我正在尝试将我的应用转换为Swift,但遇到了我不太了解的Swift错误。
在Obj-c中,我在这里有一个for in
循环:
for (MYVisitor *visitor in visitors) {
if (visitor.boxState == MYVisitorBoxStateChatting) {
[self.chattingVisitors addObject:visitor];
}
else {
[self.unknownVisitors addObject:visitor];
}
}
我迅速:
for visitor: MYVisitor in visitors {
if visitor.boxState == MYVisitorBoxStateChatting {
self.chattingVisitors.addObject(visitor)
}
else {
self.unknownVisitors.addObject(visitor)
}
}
我在迅速遇到一个错误,说:
NSArray cannot be implicitly downcast to MYVisitor, did you mean to use as to force downcast?
Xcode建议此更改:
for visitor: FHVisitor in visitors as MYVisitor {...
然后给我这个错误:MYVisitor does not conform to protocol SequenceType
最佳答案
如果visitors
是NSArray
,并且保证其所有元素都是MYVisitor
类型,则可以将数组转换为[MYVisitor]
:
for visitor in visitors as [MYVisitor] {
// ...
}
请注意,如果任何数组元素不是
MYVisitor
,这将在运行时崩溃。或者,您可以使用
if let theVisitors = visitors as? [MYVisitor] {
for visitor in theVisitors {
println(visitor.name)
}
} else {
// This is not an array of MYVisitor objects.
}
或者,您可以检查每个数组元素:
for item in visitors {
if let visitor = item as? MYVisitor {
// ...
} else {
// This is not a MYVisitor.
}
}