问题描述
我在Objective-C中有以下代码:
I have the following code in Objective-C:
- (double)readDouble
{
double value = 0.0;
if ([self read:(uint8_t *)&value maxLength:8] != 8)
{
NSLog(@"***** Couldn't read double");
}
return value;
}
它有效。但我不知道如何将其转换为Swift。这是我的代码:
It works. But I don't know how to convert it to Swift. Here is my code:
public func readDouble() -> Double {
var value : Double = 0.0
var num = self.read((uint8_t *)&value, maxLength:8) // got compiling error here!
if num != 8 {
}
}
错误信息是:
有人可以帮忙吗?谢谢
我正在使用的测试数据(1.25):
The testing data I'm using (1.25):
14 AE 47 E1 7A 14 F4 3F
更新:
一个简单的c解决方案,但是如何在Swift中执行此操作?
A simple c solution, but how to do this in Swift?
double d = 0;
unsigned char buf[sizeof d] = {0};
memcpy(&d, buf, sizeof d);
推荐答案
这应该有效:
let num = withUnsafeMutablePointer(&value) {
self.read(UnsafeMutablePointer($0), maxLength: sizeofValue(value))
}
解释: withUnsafeMutablePointer()
使用设置为地址的唯一参数
。
( $ 0
,以简写表示法)调用闭包(块)值
Explanation: withUnsafeMutablePointer()
calls the closure (block) with the only argument($0
in shorthand notation) set to the address of value
.
$ 0
的类型为 UnsafeMutablePointer< Double>
和 read()
期望
UnsafeMutablePointer< UInt8>
作为第一个参数,因此另一个转换
是必要的。然后将闭包的返回值分配给 num
。
$0
has the type UnsafeMutablePointer<Double>
and read()
expects anUnsafeMutablePointer<UInt8>
as the first argument, therefore another conversionis necessary. The return value of the closure is then assigned to num
.
这篇关于将Objective-C方法转换为Swift for NSInputStream(将字节转换为double)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!