Skip to content

Instantly share code, notes, and snippets.

@roop
Created June 27, 2014 13:42
Show Gist options
  • Save roop/4f1af9b557d4ff39aabf to your computer and use it in GitHub Desktop.
Save roop/4f1af9b557d4ff39aabf to your computer and use it in GitHub Desktop.
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