isUniquelyReferenced

func isUniquelyReferenced<T : NonObjectiveCBase>(_: inout T)

Returns true iff object is a non-@objc class instance with a single strong reference.

  • Does not modify object; the use of inout is an implementation artifact.
  • Weak references do not affect the result of this function.

Useful for implementing the copy-on-write optimization for the deep storage of value types:

mutating func modifyMe(_ arg: X) {
  if isUniquelyReferenced(&myStorage) {
    myStorage.modifyInPlace(arg)
  }
  else {
    myStorage = myStorage.createModified(arg)
  }
}

This function is safe to use for mutating functions in multithreaded code because a false positive would imply that there is already a user-level data race on the value being mutated.

Declaration

func isUniquelyReferenced<T : NonObjectiveCBase>(_ object: inout T) -> Bool