Search code examples
swiftcocoaformatted-input

Swift 4 Cocoa reading formatted data into variable


I need to read some formatted data from a string and store it in two variables. The string has this format:

data = "(1234),(-567)"

The numbers are of varying lengths and signs. I feel like this should be simple. It would be easy in C:

scanf(data, "(%d),(%d)", num1, num2)

But in Swift, I'm pulling my hair out trying to find an easy way to do this. As suggested in other answers, I've tried:

data.components(separatedBy: CharacterSet.decimalDigits.inverted)

However this overlooks minus signs. Any help is much appreciated!


Solution

  • You can use Scanner when you need scanf-like behavior:

    let data = "(1234),(-567)"
    
    var num1: CInt = 0
    var num2: CInt = 0
    let scanner = Scanner(string: data)
    if
        scanner.scanString("(", into: nil),
        scanner.scanInt32(&num1),
        scanner.scanString("),(", into: nil),
        scanner.scanInt32(&num2),
        scanner.scanString(")", into: nil)
    {
        print(num1, num2)
    } else {
        print("failed")
    }