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>(inout object: T) -> Bool