iGodric iGodric - 5 months ago 17
Swift Question

What is this NSErrorPointer type?


  1. In Swift the ampersand sign
    &
    is for
    inout
    parameters. Like


    var value = 3

    func inoutfunc(inout onlyPara: Int) {

    onlyPara++

    }

    inoutfunc(&value) // value is now 4


    That doesn't look like
    onlyPara
    is a pointer, maybe it is and get dereferences immediately when using it inside the function.
    Is onlyPara a pointer?

  2. When I don't need a
    IntPointer
    type, why are the framework methods using a
    NSErrorPointer
    type?
    Because they can't change the methods because of existing Objective-C code?

  3. But why is then Swift converting
    &error
    to
    NSErrorPointer
    , is that autoboxed?


    var errorPtr: NSErrorPointer = &error

  4. And when I have a
    NSErrorPointer
    . How do I dereference it?


    var error: NSError = *errorPtr // won't work






Maybe someone can enlighten me. Using only Swift is easy. I think the questions are one chunk of knowledge over
&
between swift and Objective-C (as the address of operator)

Answer

I suggest you read the Pointers section of the Using Swift with Cocoa and Objective-C guide: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-XID_16

There is a table at the bottom of the Pointers section, which explains how class pointers bridge to Swift pointer types. Based on that, the NSError pointer should be AutoreleasingUnsafePointer<NSError>. Searching trough the headers for NSErrorPointer yields this:

typealias NSErrorPointer = AutoreleasingUnsafePointer<NSError?>

Why the extra ? after NSError? I guess it's because NSError can also be nil.

Hope it helps!

Comments