JAL JAL - 1 month ago 6
Swift Question

Passing nil as a UnsafePointer<UInt8>

In Swift 2.2, I was able to pass in

nil
as a valid parameter to a function which requires an
UnsafePointer<UInt8>
. In Swift 3, I can no longer do that:

func myFuncThatTakesAPointer(buffer: UnsafePointer<UInt8>, length: Int) { /** **/ }

myFuncThatTakesAPointer(buffer: nil, length: 0)



Playground execution failed: error: Xcode8Playground-iOS.playground:62:33: error: nil is not compatible with expected argument type 'UnsafePointer<UInt8>'
myFuncThatTakesAPointer(buffer: nil, length: 0)
^



Am I required to specify the pointer declaration in my function as optional now?

Answer

Am I required to specify the pointer declaration in my function as optional now?

In a word, yes. From the release notes:

The types UnsafePointer, UnsafeMutablePointer, AutoreleasingUnsafeMutablePointer, OpaquePointer, Selector, and NSZone now represent non-nullable pointers—that is, pointers that are never nil. A nullable pointer is now represented using Optional, for example, UnsafePointer<Int>?.