Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
extension Array {
func sharesStorageWith(other: Array<T>) -> Bool {
let thisPtr: UnsafePointer<T> = self.withUnsafePointerToElements { return $0 }
let otherPtr: UnsafePointer<T> = other.withUnsafePointerToElements { return $0 }
return (thisPtr == otherPtr)
}
}
var a1: Array<Int> = [10, 11]
a1.append(20)
println(a1.sharesStorageWith(a1)) // true
var a2 = a1
var a3 = a1
// Now all of a1, a2 and a3 use the same
// underlying buffer.
println(a1.sharesStorageWith(a2)) // true
println(a2.sharesStorageWith(a3)) // true
a1.append(30)
// Now a1 uses a different buffer.
// a2 and a3 are still sharing data.
println(a1.sharesStorageWith(a2)) // false
println(a2.sharesStorageWith(a3)) // true
a3.unshare()
// a2 and a3 are no longer sharing data.
println(a2.sharesStorageWith(a3)) // false
var a4 = a1.copy()
// The copy() makes a4 not share a1's data
println(a1.sharesStorageWith(a4)) // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment