0

I have the following code, assuming data is of type NSData?:

    if let myData = data {
        let bytes = UnsafePointer<UInt8>(myData.bytes)
        ...
    }

How do I reduce this to a single statement, such as:

    if let bytes = UnsafePointer<UInt8>?(data?.bytes) {
        ...
    }

The above gives an error of: Cannot invoke initializer for type 'UnsafePointer<UInt8>?' with an argument list of type '(UnsafePointer<Void>?)'

1 Answers1

1

Similarly as in Getting the count of an optional array as a string, or nil, you can use the map() method of Optional:

/// If `self == nil`, returns `nil`.  Otherwise, returns `f(self!)`.
@warn_unused_result
@rethrows public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?

In your case:

if let bytes = (data?.bytes).map({ UnsafePointer<UInt8>($0) }) {

}

(data?.bytes) uses optional chaining and has the type UnsafePointer<Void>?. The map function is used to convert that to UnsafePointer<UInt8>?, which is finally unwrapped with the optional binding.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382