作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个用 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/
我是一名优秀的程序员,十分优秀!