0

I am attempting to take in a string literal value like

var s: String = "0.9 1.2 4.8 0.4 3.2 7.9"

And convert it into an array of float3s like this

var f: [float3] = [float3(0.9, 1.2, 4.8), float3(0.4, 3.2, 7.9)]

So far I have written an extension function for string that looks like this

extension String {
    func toFloat3Array()->[float3]{
        var result = [float3]()

        let pointArray: [Float] = self.split(separator: Character(" ")).map { Float($0) ?? 0.0 }
        for var i in 0..<pointArray.count - 2 {
            result.append(float3(pointArray[i++], pointArray[i++], pointArray[i++]))
        }

        return result
    }
}

*Note: I have created an operator overload for i (++) that returns the value then increases it like you would see in java.

This works just fine, but I am hoping that there is a better way to map the values from the string array into the float3 array :) Thank you!

twohyjr
  • 120
  • 9
  • string->float is *hard* to implement with full accuracy in the general case of very large / small numbers, or very long fractional parts where only the 50th or w/e digit pushes it above the threshold to round to the next representable `float`. Do you have any kind of reduced accuracy requirements, or input format simplifications like always 2-digit numbers like x.y? See [Where can I find the world's fastest atof implementation?](https://stackoverflow.com/q/98586) for ideas. – Peter Cordes Sep 04 '18 at 01:31
  • Related Swift question: [is it possible convert String to simd\_float4x4 ? ( iOS 12 )](https://stackoverflow.com/q/51579408) – Peter Cordes Sep 04 '18 at 01:31
  • See [Entering and dealing with floating point numbers on IEEE 784 with assembler (NASM 32bit)](https://stackoverflow.com/q/32836428) for the low level details of how full-precision atof (string->float) is implemented. http://www.exploringbinary.com/how-glibc-strtod-works/ and http://www.exploringbinary.com/how-strtod-works-and-sometimes-doesnt/ – Peter Cordes Sep 04 '18 at 01:36
  • 1
    This appears to be a request for a code review. That's best done at https://codereview.stackexchange.com – rmaddy Sep 04 '18 at 02:02

0 Answers0