类型NSArray不能隐式转发

时间:2015-01-06 19:09:44

标签: ios objective-c swift

我正在努力将我的应用转换为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

1 个答案:

答案 0 :(得分:5)

如果visitorsNSArray并且保证所有元素都是 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.
    }
}