我有一个用Objetive-C构建的框架。该框架用于连接蓝牙设备并与之交互。

在演示代码中,Objetive-C委托函数如下所示。该演示代码由框架的创建者提供。

-(void)babyScaleManagerScanDevices:(NSArray<ELBabyScaleDeviceModel *> *)babyScaleDevices{
    NSLog(@"babyScaleManagerScanDevices = %@",babyScaleDevices);
    ELBabyScaleDeviceModel *model = babyScaleDevices.firstObject;
}


我已经在快速项目中包含了该框架,并导入了标头。我正在尝试通过以下方法获得相同的结果:

func babyScaleManagerScanDevices(_ babyScaleDevices: [ELBabyScaleDeviceModel]?) {
    guard let device = babyScaleDevices?.first else {
      print("Error unwrapping first device")
      return
    }
    print("Device: \(String(describing: device))")
  }


我得到以下异常:

Thread 1: Precondition failed: NSArray element failed to match the Swift Array Element type
Expected ELBabyScaleDeviceModel but found ELPeripheralModel

Precondition failed: NSArray element failed to match the Swift Array Element type
Expected ELBabyScaleDeviceModel but found ELPeripheralModel: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1100.2.274.2/swift/stdlib/public/core/ArrayBuffer.swift, line 354


检查babyScaleDevices数组显示:

babyScaleDevices    [ELBabyScaleDeviceModel]?   1 value some
[0] ELPeripheralModel * 0x281cae100 0x0000000281cae100


结果与Objetive-C和我的Swift项目中的演示代码相同。

ELBabyScaleDeviceModel.h看起来像:

#import "ELPeripheralModel.h"

NS_ASSUME_NONNULL_BEGIN

@interface ELBabyScaleDeviceModel : ELPeripheralModel

@end

NS_ASSUME_NONNULL_END


您能解释一下发生了什么吗?

最佳答案

您必须将Array指定为NSArray

将此行添加到您的代码中

let devices = babyScaleDevices as NSArray


你可以试试这个

func babyScaleManagerScanDevices(_ babyScaleDevices: [ELBabyScaleDeviceModel]?) {
let devices = babyScaleDevices as NSArray
guard let device = devices.firstObject else {
    print("Error unwrapping first device")
    return
}
print("Device: \(String(describing: device))")


}

然后检查此-> Array vs NSArray

09-18 09:26