How do I sscanf()?

I'm trying to convert this to something usable in swift:


sscanf(scanStr, "%4d%2d%2dT%2d%2d%2d", &year, &month, &day, &hour, &minutes, &seconds


I explicitly do not want to use an NSDateFormatter as I have a bunch of different types I'm comparing against.

Accepted Answer

It’s not possible to call C varargs routines directly from Swift. In your specific case I’d probably use

strptime
. However, if you’re absolutely committed to
sscanf
then you’ll need to use C or Objective-C to write it in a Swift-compatible manner.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Well, technically you can via the varargs variants, but it's pretty unwieldy:


"20151130T052035".cStringUsingEncoding(NSUTF8StringEncoding)?.withUnsafeBufferPointer { buf in
    let scanStr = buf.baseAddress
   
    var year: Int32 = 0
    var month: Int32 = 0
    var day: Int32 = 0
    var hour: Int32 = 0
    var minutes: Int32 = 0
    var seconds: Int32 = 0
   
    withUnsafeMutablePointers(&year, &month, &day) { yearPtr, monthPtr, dayPtr in
        withUnsafeMutablePointers(&hour, &minutes, &seconds) { hourPtr, minPtr, secPtr in
            let args: [CVarArgType] = [yearPtr, monthPtr, dayPtr, hourPtr, minPtr, secPtr]
           
            if vsscanf(scanStr, "%4d%2d%2dT%2d%2d%2d", getVaList(args)) < 6 {
                print("Something went wrong!")
            } else {
                print("year: \(year) month: \(month) day: \(day) hour: \(hour) minutes: \(minutes) seconds: \(seconds)")
            }
        }
    }
}
How do I sscanf()?
 
 
Q