Last active
April 5, 2018 07:29
-
-
Save JayachandraA/53bec323ef41202636a9cafb83ad6ea9 to your computer and use it in GitHub Desktop.
Difference between struct and class in swift4.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//finding memory location of stack and heap | |
func addressHeap<T: AnyObject>(o: T) -> Int { | |
return unsafeBitCast(o, to: Int.self) | |
} | |
func addressStack(o: UnsafeRawPointer) -> Int { | |
return Int(bitPattern: o) | |
} | |
//structure is a value based | |
struct A{ | |
var type: String | |
init(type: String) { | |
self.type = type | |
} | |
} | |
var a = A(type: "Struct") | |
var a1 = a //copy the value | |
a1.type = "Struct1" | |
print(addressStack(o: &a)) // -> 4708867904 | |
print(addressStack(o: &a1)) // -> 4708867928 | |
print(a.type) // -> Struct | |
print(a1.type) // -> Struct1 | |
print("\n") | |
//class is reference based | |
class B{ | |
var type: String | |
init(type: String) { | |
self.type = type | |
} | |
} | |
let b = B(type: "Class") | |
let b1 = b // copy the address | |
b1.type = "Class1" | |
print(addressHeap(o: b)) // -> 105553116575008 | |
print(addressHeap(o: b1)) // -> 105553116575008 | |
print(b.type) // -> Class1 | |
print(b1.type) // -> Class1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment