【发布时间】:2019-01-08 19:53:46
【问题描述】:
所以我有一个 NSArrays 加载了保存在 Shot 对象上的俯仰和偏航值。
@interface Shot : NSObject
@property (strong, nonatomic) NSArray *pitch;
@property (strong, nonatomic) NSArray *yaw;
我正在尝试快速处理一些数字并遇到一个非常奇怪的问题:
let pitch = Array(shot.recoil_pitch[0..<10]) as! [Float]
let yaw = Array(shot.recoil_yaw[0..<10]) as! [Float]
由于某种我无法弄清楚的原因,第一行运行良好。但是,第二行会抛出 Fatal error: Unable to bridge NSNumber to Float。
当我在调试器中检查 shot.recoil_pitch[0..<10] 时,我得到:
- 0 : 0
- 1 : -0.1355667114257812
- 2 : -2.584976196289062
- 3 : -2.238974571228027
- 4 : -1.606719017028809
- 5 : -1.54025936126709
- 6 : -1.570234298706055
- 7 : -1.544057846069336
- 8 : -1.323789596557617
- 9 : -1.073002815246582
当我检查 shot.recoil_yaw[0..<10] 时,我得到:
- 0 : 0
- 1 : 0.017406463623046875
- 2 : -0.07871246337890625
- 3 : 0.004611968994140625
- 4 : 0.0446014404296875
- 5 : -0.0008544921875
- 6 : 0.010448455810546875
- 7 : 0.01015472412109375
- 8 : -0.002346038818359375
- 9 : -0.0569610595703125
关于为什么我可能会收到此错误的任何想法?
【问题讨论】:
-
当您检查
recoil_yaw时,它会为您提供任何类型信息吗?如果您正在处理来自 Objective-C 的内容,最好将它们转换为原生 Objective-C 类NSNumber,然后使用成员floatValue将它们映射到Float。 -
recoil_yaw上的下标返回类型是什么?最好使用map而不是强制转换为Array(shot.recoil_pitch[0..<10]).map{ $0.floatValue } -
这也可能是相关的:stackoverflow.com/a/50019421/1484378
-
@Kamran - 没错,但如果不将
$0转换为NSNumber,他将无法直接调用floatValue;或 (b) 在他的 Objective-C 标头中使用轻量级泛型,例如@property (strong, nonatomic) NSArray<NSNumber *> *recoil_pitch.
标签: objective-c swift nsnumber bridging