gpt4 book ai didi

ios - 我不明白为什么 Objective-C 委托(delegate)函数可以工作而 Swift 委托(delegate)函数会崩溃。你能给我解释一下吗?

转载 作者:行者123 更新时间:2023-11-29 05:16:58 28 4
gpt4 key购买 nike

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

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

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

我已将框架包含在我的 swift 项目中并导入了 header 。我试图通过这样做获得相同的结果:

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

关于ios - 我不明白为什么 Objective-C 委托(delegate)函数可以工作而 Swift 委托(delegate)函数会崩溃。你能给我解释一下吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59087899/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com