Skip to content

Instantly share code, notes, and snippets.

@pofat
Created September 29, 2019 08:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pofat/0c5d0ab99c95bb7b9663b57b550feea4 to your computer and use it in GitHub Desktop.
Save pofat/0c5d0ab99c95bb7b9663b57b550feea4 to your computer and use it in GitHub Desktop.
Discuss how closure capturing and capture list works
import Foundation
// struct for printing out instance address
struct MemoryAddress<T>: CustomStringConvertible {
let intValue: Int
var description: String {
let length = 2 + 2 * MemoryLayout<UnsafeRawPointer>.size
return String(format: "%0\(length)p", intValue)
}
// for struct
init(of structPointer: UnsafePointer<T>) {
intValue = Int(bitPattern: structPointer)
}
}
extension MemoryAddress where T: AnyObject {
// for class
init(of classInstance: T) {
intValue = unsafeBitCast(classInstance, to: Int.self)
}
}
/// struct example
var a = 1, b = 1
print("address of a: \(MemoryAddress(of: &a))")
print("address of b: \(MemoryAddress(of: &b))")
var captureList = { [a] in
print("[In closure] address of b: \(MemoryAddress(of: &b))")
print("[In closure] a: \(a), b: \(b)")
}
let strongRef = {
a += 1
b += 1
}
strongRef()
print("a: \(a), b: \(b)")
captureList()
// class example
print("============ Reference ============")
class aClass{
var value = 1
}
var c1 = aClass()
var c2 = aClass()
var copyReference = { [c1] in // copy a reference to c1 instance
print("[In copy clsoure] c1 address : \(MemoryAddress(of: c1))")
print("[In copy clsoure] c2 address : \(MemoryAddress(of: c2))")
}
var weakCast = { [weak c1] in
print("[In clsoure] c1 address : \(MemoryAddress(of: c1!))")
print("[In clsoure] c2 address : \(MemoryAddress(of: c2))")
c1?.value += 1
}
print(" c1 address : \(MemoryAddress(of: c1))")
print(" c2 address : \(MemoryAddress(of: c2))")
copyReference()
weakCast()
print("c1 retain count : \(CFGetRetainCount(c1))") // c1 has one more retain count than c2
print("c2 retain count : \(CFGetRetainCount(c2))")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment