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

Tim Vermeulen tvermeulen at me.com
Mon Jun 27 19:14:47 CDT 2016


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?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160628/203755b0/attachment.html>


More information about the swift-users mailing list