Does AutoreleasingUnsafeMutablePointer<Type> have to be optional?

In all the examples for AutoreleasingUnsafeMutablePointer, the type is always optional, for example AutoreleasingUnsafeMutablePointer<NSDate?>

Does this have to be the case, and if so, why?

Replies

Consider this code:

import Foundation

var inStream: InputStream? = nil
var outStream: OutputStream? = nil
Stream.getStreamsToHost(
    withName: "example.com",
    port: 80,
    inputStream: &inStream,
    outputStream: &outStream
)

Logically, the value you pass to the

inputStream
parameter must be of type
InputStream?
because:
  • you need an

    inStream
    that you can pass in to the parameter
  • Swift requires that each value be initialised

  • for something like a stream, there’s no obvious non-nil value you could use

Also, given this construct’s Objective-C heritage, the ‘returned’ value is always going to be a class instance anyway.

Share and Enjoy

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

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

That sort of makes sense, but why wouldn't UnsafeMutablePointer work there?

why wouldn't UnsafeMutablePointer work there?

Because there are semantic differences related to reference counting. The docs do a pretty good job of covering this difference.

Share and Enjoy

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

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