Is it safe to discard returned value of Unmanaged.retain()?

The retain function of Unmanaged returns a new Unmanaged.

The documentation doesn't state why, and the function isn't annotated with @discardableResult.

I looked at the implementation and it doesn't seem to mutate the struct (it's not mutating anyway) and it just returns self, which looks to be basically the same "pointer" to the unmanaged reference.

Can I safely discard the return value then? Or is there an undocumented thing I must do with the returned Unmanaged?


It's likely a tradition modelled after Obj-C retain, which historically returned self for:

I'd say in Swift it could have been @discardableResult (and I believe making it discardableResult is not a breaking change, so we could still do it at some point).

Of course you can override -retain to return something other than self, so it’s important that Swift passes the return value through for interop with pathological libraries.

Thanks for your answer, I will do _ = unmanaged.retain() to silence the warning until @discardableResult is added (if it's ever added).

Just to confirm, here you were talking about overriding NSObject's retain.. Note that returning anything but "self" from an override would be in a direct contradiction to the documentation: