Search code examples
swiftcocoacocoa-touchnsscanner

NSScanner scanDouble UnsafeMutablePointer


I'm using NSScanner to scan a string and extract a double from it. Here's my sandboxed code to try and solve the problem

let string = "maxage=1234567890"
let scanner2 = NSScanner(string: string)
scanner2.scanUpToString("=", intoString: nil)
scanner2.scanString("=", intoString: nil)
let maxage2:UnsafeMutablePointer<Double> = UnsafeMutablePointer<Double>()
scanner.scanDouble(maxage2)
print(scanner2.scanLocation)
print(maxage2)

it prints:

7
0x0000000000000000

So the first two calls to consume the first part of the string work, but then scanning a double isn't working.

I've seen other solutions that look like this:

var double = 0.0
scanner.scanDouble(&double)

But that doesn't seem to work in Swift anymore. Maybe it did in an earlier version?

How can I fix this?


Solution

  • I wonder if you accidentally had a typo there by using scanner.scanDouble instead of scanner2.scanDouble?

    This works for me:

    let string = "maxage=1234567890"
    let scanner2 = NSScanner(string: string)
    scanner2.scanUpToString("=", intoString: nil)
    scanner2.scanString("=", intoString: nil)
    var aDoubleNumber = 0.0
    scanner2.scanDouble(&aDoubleNumber)
    print(scanner2.scanLocation)
    print(aDoubleNumber)