iosswiftnsinputstream

Convert an Objective-C method into Swift for NSInputStream (convert bytes into double)


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;
}

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 {

    }
}

The error message is:

Cannot invoke '&' with an argument list of type '($T4, maxLength: IntegerLiteralConvertible)'

Can anybody help? Thanks

The testing data I'm using (1.25):

14 AE 47 E1 7A 14 F4 3F

UPDATE:

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);

Solution

  • This should work:

    let num = withUnsafeMutablePointer(&value) {
        self.read(UnsafeMutablePointer($0), maxLength: sizeofValue(value))
    }
    

    Explanation: withUnsafeMutablePointer() calls the closure (block) with the only argument ($0 in shorthand notation) set to the address of value.

    $0 has the type UnsafeMutablePointer<Double> and read() expects an UnsafeMutablePointer<UInt8> as the first argument, therefore another conversion is necessary. The return value of the closure is then assigned to num.