我正在努力将我的应用转换为swift,但我遇到了一个我还不太了解的快速错误。
在Obj-c中我有一个for in
循环:
for (MYVisitor *visitor in visitors) {
if (visitor.boxState == MYVisitorBoxStateChatting) {
[self.chattingVisitors addObject:visitor];
}
else {
[self.unknownVisitors addObject:visitor];
}
}
在swift中我有:
for visitor: MYVisitor in visitors {
if visitor.boxState == MYVisitorBoxStateChatting {
self.chattingVisitors.addObject(visitor)
}
else {
self.unknownVisitors.addObject(visitor)
}
}
我在swift中收到错误消息: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
答案 0 :(得分:5)
如果visitors
是NSArray
并且保证所有元素都是
MYVisitor
类型,然后您可以将数组强制转换为[MYVisitor]
:
for visitor in visitors as [MYVisitor] {
// ...
}
请注意,如果任何数组元素不 a 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.
}
}