Do i need to put any OS Error handling for Unmanaged.passRetain (obj) or Unmanaged.takeRetain (objptr)

In below Swift code , is there any possiblities of failure of Unmanaged.passRetain and Unmanaged.takeRetain calls ?

// can below call fail (constructor returns nil due to OS or language error) and do i need to do explicit error handling here?

let str = TWSwiftString(pnew)
        
// Increasing RC by 1
// can below call fail (assuming str is valid) and do i need to do explicit error handling for the same ?

let ptr:UnsafeMutableRawPointer? = Unmanaged.passRetained(str).toOpaque()             

// decrease RC by 1
// can below call fail (assuming ptr is valid) ? and do i need to do explicit error handling

Unmanaged<TWSwiftString>.fromOpaque(pStringptr).release()                 

Answered by DTS Engineer in 814010022

Check out the types for the various routines you’re using:

  • passRetained(_:) returns Unmanaged<Instance>. That’s not optional.

  • toOpaque() returns UnsafeMutableRawPointer. That’s not optional either.

  • fromOpaque(_:) returns Unmanaged<Instance>. Again, not optional.

  • Likewise for takeRetainedValue().

No optionals means no possibility of failure.

Well, this could fail horribly if you try to go from an UnsafeMutableRawPointer to an object and the original UnsafeMutableRawPointer isn’t valid. But that’s not something that these routines can detect, which is why they return non-optional values.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer

Check out the types for the various routines you’re using:

  • passRetained(_:) returns Unmanaged<Instance>. That’s not optional.

  • toOpaque() returns UnsafeMutableRawPointer. That’s not optional either.

  • fromOpaque(_:) returns Unmanaged<Instance>. Again, not optional.

  • Likewise for takeRetainedValue().

No optionals means no possibility of failure.

Well, this could fail horribly if you try to go from an UnsafeMutableRawPointer to an object and the original UnsafeMutableRawPointer isn’t valid. But that’s not something that these routines can detect, which is why they return non-optional values.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Do i need to put any OS Error handling for Unmanaged.passRetain (obj) or Unmanaged.takeRetain (objptr)
 
 
Q