类型 NSArray 不能被隐式向下转换

Type NSArray cannot be downcast implicitly

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

如果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.
    }
}