1

I have an array of double values that should be stored in an external file. I convert the array to NSMutableData and save the data to disk.

Some of the double values are either missing (nil) or are zero (0.0). Missing values can be replaced by 0.0 or by the maximum double representation.

But Double has no max value (like Int.max) and 0.0 values are interpreted by NSData as termination bytes. So every time a 0.0 value is encountered, the data ends too soon.

var description: String {
    var output: String = ""
    for value in self
    {
        output = output + "\(value)\n"
    }
    return output
}

var count : Int { return data.length/sizeof(Double) }

func append(var value: Double)
{
    self.data.appendBytes(&value, length: self.size)
}

subscript(index: Int) -> Double?
{
    assert(index < self.count, "index exceeds bounds")
    var output : Double?
    self.data.getBytes(&output, range: NSRange(location: index * self.size, length: self.size))
    return output
}

edit:

D'Oh, I was using generate to print out the values, and GeneratorOf stops after the first nil value. Still, what would be a good way to represent a nil value to differentiate from 0.0?

func generate() -> GeneratorOf<Double>
{
    var index = 0
    var count = self.counter
    return GeneratorOf<Double> {
        if index < count
        {
            return self[index++]
        }
        return nil
    }
}

edit2

It's Double.infinity rather than Int.max

I need to wake up now.

user965972
  • 2,489
  • 2
  • 23
  • 39
  • 1
    *"0.0 values are interpreted by NSData as termination bytes"* – No. NSData does not interpret the bytes at all. – Martin R Apr 14 '15 at 08:52
  • Well then why do I only get the first few values back? ... oh... d'oh, the generate function (SequenceType) terminates when it encounters a nil value. – user965972 Apr 14 '15 at 09:09

1 Answers1

2

The only solution that comes in my mind here is to wrap the double using NSNumber, so you can have 0.0 correctly handled and for nulls you can then use NSNull. Is there any specific reason you are not using NSNumber?

bontoJR
  • 6,995
  • 1
  • 26
  • 40