Search code examples
swiftparsingswift5nsscanner

Swift: Scanner scanDouble doesn't work correctly


I am working on String parse in swift and I use Scanner. But the main problem is that scanner.scanDouble and scanner.scanFloat doesn't work. Here is my code:

var magnitude: Double = 0
let scanner = Scanner(string: magString) // magString sample values  are "E1.00 INCH", "E1.50 INCH", "M0.88 INCH"

scanner.scanDouble(&magnitude)

But after running app, magnitude is 0.0

How can I get 1.00, 1.50 and 0.88 from string?


Solution

  • scanDouble chokes on the "E" and "M" prefixes. If your know what these are, you can add them to the ignore list:

    for str in ["E1.00 INCH", "E1.50 INCH", "M0.88 INCH"] {
        let scanner = Scanner(string: str)
        scanner.charactersToBeSkipped = CharacterSet(charactersIn: "EM")
        var magnitude = 0.0
        if scanner.scanDouble(&magnitude) {
            print(magnitude)
        }
    }
    

    or, if you know it's only one leading character, remove it using dropFirst:

    for str in ["E1.00 INCH", "E1.50 INCH", "M0.88 INCH"] {
        let scanner = Scanner(string: String(str.dropFirst()))
        var magnitude = 0.0
        if scanner.scanDouble(&magnitude) {
            print(magnitude)
        }
    }
    

    also, you should check the return value of scanDouble. BTW, this method is deprecated as of iOS 13.