我不明白为什么 Objective-C 委托函数有效而 Swift 委托函数崩溃。你能给我解释一下吗?

I don't understand why an Objective-C delegate function works and a Swift delegate function crash. Can you explain to me?

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

在演示代码中,Objetive-C 委托函数看起来像。演示代码由框架的创建者提供。

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

我已将该框架包含在我的 swift 项目中并导入了 headers。我正在尝试通过以下方式获得相同的结果:

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 项目中的演示代码中是相同的。

class 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))")

}

然后检查这个 ->

尝试改变

func babyScaleManagerScanDevices(_ babyScaleDevices: [ELBabyScaleDeviceModel]?)

func babyScaleManagerScanDevices(_ babyScaleDevices: [Any]?)

并将特定元素转换为 ELBabyScaleDeviceModel,例如 for。 似乎这个框架的创建者将 ELPeripheralModel 放在数组中而不是 ELBabyScaleDeviceModel

我认为这正是代码桥接到 Swift 的方式。

能否尝试将类型指定为[ELPeripheralModel]然后进行转换?

func babyScaleManagerScanDevices(_ babyScaleDevices: [ELPeripheralModel]?) {

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