[swift-users] Checking whether an object is uniquely referenced, using a weak reference to it

Jordan Rose jordan_rose at apple.com
Mon Jun 27 20:17:30 CDT 2016


Hi, Tim. The purpose of the isUniquelyReferenced checks is to see whether any changes to the properties of the object can be observed from elsewhere in this program. Therefore, I would expect it to return ‘false’ when there are weak (or unowned) references present, i.e. I think the bug is that we don’t consider weak or unowned references to count for this check.

If my understanding of the intended behavior is correct, then it doesn’t make sense to check for a uniquely-referenced object through a weak (or unowned) reference, because if that were the only reference, then the object would have already been deallocated.

The particular technical reason for the check failing is related to the inout, as you say: in order to pass the reference to the function inout, it has to be loaded into a strong reference first. The reason the inout is there at all is because otherwise the check would fail: there would be a reference from outside the function in addition to the one for the argument.

Hope that clears things up, and if you agree with my interpretation about weak and unowned references, please file a bug at bugs.swift.org <http://bugs.swift.org/>!
Jordan


> On Jun 27, 2016, at 17:14, Tim Vermeulen via swift-users <swift-users at swift.org> wrote:
> 
> class EmptyClass {}
> 
> var strongReference = EmptyClass()
> weak var weakReference = strongReference
> 
> print(isUniquelyReferencedNonObjC(&strongReference)) // true
> print(isUniquelyReferencedNonObjC(&weakReference))   // false
> 
> I expected both print statements to print true.
> 
> I realise that this is probably a known limitation of this function. After all, if it worked with weak references too, there’s no point for the parameter to be inout:
> 
> func wrappedIsUniquelyReferencedNonObjC<T: AnyObject>(_ object: T) -> Bool {
>     weak var weakObject = object
>     return isUniquelyReferencedNonObjC(&weakObject)
> }
> 
> So the fact that this function takes an inout parameter hints at the fact that it doesn’t work with weak references. If my reasoning is correct, it would be nice if the docs stated that it only works with strong references to objects. :)
> 
> My question is, is it possible at all to use a weak reference to check whether an object is uniquely referenced or not? Since this approach doesn’t seem to work, I guess it is impossible?
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160627/2dc93e6f/attachment.html>


More information about the swift-users mailing list