【问题标题】:Cannot convert value of type 'NSArray.Element' to expected argument无法将“NSArray.Element”类型的值转换为预期参数
【发布时间】:2021-04-18 10:07:16
【问题描述】:

我有一个用 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。有没有办法解决这个问题?

【问题讨论】:

  • 这里 Beacon 是你的模型类??
  • 是的,是一个自定义类

标签: objective-c swift delegates nsmutablearray protocols


【解决方案1】:

你可以试试

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

【讨论】:

  • 但是做“func onBeaconDetected(_detectedBeacons:[Beacon])”,我得到不符合协议'ScanBeaconsDelegate',我无法更改静态库代码。
  • 完美!非常感谢您的帮助
猜你喜欢
  • 2016-03-21
  • 2016-07-27
  • 2016-07-02
  • 1970-01-01
  • 1970-01-01
  • 2020-03-01
  • 2016-08-01
  • 2017-02-07
  • 1970-01-01
相关资源
最近更新 更多