我有一个用 Objetive-C 构建的框架。该框架用于连接蓝牙设备并与之交互。
在演示代码中,Objetive-C 委托(delegate)函数如下所示。演示代码由框架创建者提供。
-(void)babyScaleManagerScanDevices:(NSArray *)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
nghiên cứu 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
@kết thúc
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
Tôi là một lập trình viên xuất sắc, rất giỏi!