无法将NSData Objective-C代码转换为Swift [英] Trouble converting NSData Objective-C code to Swift

查看:77
本文介绍了无法将NSData Objective-C代码转换为Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将Objective-C片段转换为使用 NSData CoreBluetooth 的Swift时遇到了问题.我看过这个问题和一个与其他在Swift中处理 NSData 的人,但是没有成功.

I've been having issues converting an Objective-C snippet to Swift that uses NSData and CoreBluetooth. I have looked at this question and a couple others dealing with NSData in Swift but haven't had any success.

Objective-C代码段:

- (CGFloat) minTemperature
{
    CGFloat result = NAN;
    int16_t value = 0;

    // characteristic is a CBCharacteristic
    if (characteristic) { 
        [[characteristic value] getBytes:&value length:sizeof (value)];
        result = (CGFloat)value / 10.0f;
    }
    return result;
}

到目前为止,我在Swift中所拥有的(不起作用):

What I have so far in Swift (not working):

func minTemperature() -> CGFloat {
    let bytes = [UInt8](characteristic?.value)
    let pointer = UnsafePointer<UInt8>(bytes)
    let fPointer = pointer.withMemoryRebound(to: Int16.self, capacity: 2) { return $0 }
     value = Int16(fPointer.pointee)

    result = CGFloat(value / 10) // not correct value

    return result
}

这里的逻辑看起来不对吗?谢谢!

Does the logic look wrong here? Thanks!

推荐答案

一个错误

let fPointer = pointer.withMemoryRebound(to: Int16.self, capacity: 2) { return $0 }

因为回弹指针 $ 0 仅在闭包内部有效,并且必须不能传递到外面.此外,对于单个 Int16 值.另一个问题是

because the rebound pointer $0 is only valid inside the closure and must not be passed to the outside. Also the capacity should be 1 for a single Int16 value. Another problem is the integer division in

result = CGFloat(value / 10)

会截断结果(如The4kman观察到的).

which truncates the result (as already observed by the4kman).

不必从数据创建 [UInt8] 数组,可以改用 Data withUnsafeBytes()方法.

Creating an [UInt8] array from the data is not necessary, the withUnsafeBytes() method of Data can be used instead.

最后,如果没有,您可以返回 nil (而不是"not a number")特征值给出:

Finally you could return nil (instead of "not a number") if no characteristic value is given:

func minTemperature() -> CGFloat? {
    guard let value = characteristic?.value else {
        return nil
    }
    let i16val = value.withUnsafeBytes { (ptr: UnsafePointer<Int16>) in
        ptr.pointee
    }
    return CGFloat(i16val) / 10.0
}

这篇关于无法将NSData Objective-C代码转换为Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆