Skip to content

Instantly share code, notes, and snippets.

@TerryCK
Created December 11, 2017 15:41
Show Gist options
  • Save TerryCK/a7bbb4541cb4e9e93038a9e80828aaa4 to your computer and use it in GitHub Desktop.
Save TerryCK/a7bbb4541cb4e9e93038a9e80828aaa4 to your computer and use it in GitHub Desktop.
Discuss about Swift threadSafety with struct and memory address
import Foundation
var array = [1,2,3,4]
// read the `array` to property `getArray`, to properties in the same heap momery address, not copy data form `array` to `getArray` right now.
let getArray = array
array
getArray
address(of: array)
address(of: getArray)
array.append(10)
// ---------------- after modified -----------------
// here is new copy from `array` to `getArray` because `array` is modified, by line 13, COW (Copy On Write)
array
getArray
address(of: array)
address(of: getArray)
func sizeof<T> (_ : T) -> Int
{
return (MemoryLayout<T>.size)
}
func sizeof<T> (_ value : [T]) -> Int
{
return (MemoryLayout<T>.size * value.count)
}
func address(of o: UnsafeRawPointer) -> String {
return unsafeBitCast(o, to: Int.self).toHexString
}
func addressHeap<T: AnyObject>(_ o: T) -> String {
return unsafeBitCast(o, to: Int.self).toHexString
}
extension Int {
var toHexString: String {
return NSString(format: "%p", self) as String
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment