斯威夫特"扫描仪"陷入无限循环

时间:2018-05-06 01:08:55

标签: ios swift

我的CSV格式与此类似

"1.0","remainder1",
"2.0","remainder2",
"3.0","remainder3",
"4.0","remainder4",
"5.0","remainder5"

我希望使用以下内容扫描和打印值:

    var textScanner: Scanner = Scanner(string: textToScan)
    textScanner.charactersToBeSkipped = CharacterSet(charactersIn: "\",")

    var value: Double = 0.0
    var remainder: NSString?

    while !textScanner.isAtEnd {

        textScanner.scanDouble(&value)
        textScanner.scanUpTo("\n", into: &remainder)

        print("value \(value)")
        print("remainder \(remainder)")

        print("\n newline \n")
    }

它正确地发现value是双精度而remainder是一个字符串。但它陷入了无限循环,并一遍又一遍地打印相同的结果。

如果我从扫描一个双字符串变为字符串,那么它会向前移动并正确完成:

textScanner.scanUpTo(",", into: &value)

但我真的想直接将第一个值扫描到double而不是string,然后由于特殊原因将其转换回double

我在第一次实施中遗漏了什么才能让它发挥作用?

谢谢!

1 个答案:

答案 0 :(得分:1)

一些评论:

  1. 请务必检查scan...的返回值,以确保它实际扫描了您的想法。
  2. scanUpTo不包含您要扫描的字符串。因此,扫描仪指向换行符,而不是换行符后面的字符。
  3. 仅在您需要的地方声明变量。
  4. 您的代码应该更像这样:

    var textScanner: Scanner = Scanner(string: csv)
    textScanner.charactersToBeSkipped = CharacterSet(charactersIn: "\",")
    
    var cnt = 0 // for testing only
    
    while !textScanner.isAtEnd {
        var value: Double = 0.0
        var remainder: NSString?
    
        if textScanner.scanDouble(&value) && textScanner.scanUpTo("\n", into: &remainder) {
            // Ignore the newline
            textScanner.scanString("\n", into: nil)
    
            print("value \(value)")
            print("remainder \(remainder)")
    
            print("\n newline \n")
        } else {
            print("oops")
        }
    
        // For testing to avoid infinite loop    
        cnt += 1
        if cnt > 10 {
            break
        }
    }