Search code examples
swiftcocoaunsafemutablepointer

Swift syntax: UnsafeMutablePointers in CGPDFDocument.getVersion


Can anyone explain how I'm supposed to use the method 'getVersion' for CGPDFDocument in Swift? Apple's documentation gives:

func getVersion(majorVersion: UnsafeMutablePointer<Int32>, 
   minorVersion: UnsafeMutablePointer<Int32>)

"On return, the values of the majorVersion and minorVersion parameters are set to the major and minor version numbers of the document respectively."

So I supply two variables as arguments of the function, and they get filled with the values on exit? Do they need to point to something in particular before the method is called? Why not just type them as integers, if that's what the returned values are?


Solution

  • You use it like this:

    var major: Int32 = 0
    var minor: Int32 = 0
    document.getVersion(majorVersion: &major, minorVersion: &minor)
    print("Version: \(major).\(minor)")
    

    The function expects pointers, but if you pass in plain Int32 variables with the & operator, the Swift compiler is smart enough to call the function with pointers to the variables. This is documented in Using Swift with Cocoa and Objective-C: Interacting with C APIs.

    The main reason the function works like this is probably that it's a very old C function that has been imported into Swift. C doesn't support tuples as return values; using pointers as in-out parameters is a way to have the function return more than one value. Arguably, it would have been a better design to define a custom struct for the return type so that the function could return the two values in a single type, but the original developers of this function apparently didn't think it was necessary — perhaps unsuprisingly, because this pattern is very common in C.