首页 > 解决方案 > 无法将“NSArray.Element”类型的值转换为预期参数

问题描述

我有一个用 Objective C 编写的静态库,其中我有一个协议来获取监视区域结果的回调。

@protocol ScanBeaconsDelegate <NSObject>
@required
- (void) onBeaconDetected: (NSMutableArray <Beacon*> *) detectedBeacons
@end

然后,当我想使用 de 委托方法时,我会这样使用:

- (void) onBeaconDetected: (NSMutableArray <Beacon*> *) detectedBeacons
{
    for(Beacon *b in detectedBeacons)
    {
        //do staff
    }
}

现在,我在 Swift 中开发一个项目,我想以相同的方式使用协议,但是 xCode 像这样引用委托方法:

 func onBeaconDetected(_ detectedBeacons: NSMutableArray!) {
    for beacon: Beacon in detectedBeacons
    {
        //do staff
    }
}

我不知道如何将检测到的Beacons 数组转换为信标对象,我得到一个“无法将序列元素类型'NSArray.Element'(又名'Any')转换为预期类型'Beacon'”。

我很迷茫,因为这是我第一次接触 swift。有没有办法解决这个问题?

标签: objective-cswiftdelegatesnsmutablearrayprotocols

解决方案


你可以试试

func onBeaconDetected(_ detectedBeacons: NSMutableArray!) {
  for beacon in (detectedBeacons as! [Beacon]) {
    //do staff
  }
}

推荐阅读