Skip to content

Instantly share code, notes, and snippets.

@MrSmart00
Last active June 11, 2021 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrSmart00/99dc39edc87bdb442dc0d46f0b687a62 to your computer and use it in GitHub Desktop.
Save MrSmart00/99dc39edc87bdb442dc0d46f0b687a62 to your computer and use it in GitHub Desktop.
Escaping内のキャプチャ挙動確認用 via Playground
import UIKit
import UIKit
class HogeClass {
let text = "weak"
func print(handler: @escaping (String) -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
handler(self?.text ?? "")
}
}
deinit {
Swift.print("Bye, \(text)")
}
}
var hoge: HogeClass? = .init()
hoge?.print(handler: { print("Hello, \($0)") })
hoge = nil
class HogeClass2 {
let text = "strong"
func print(handler: @escaping (String) -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
handler(self.text)
}
}
deinit {
Swift.print("Bye, \(text)")
}
}
var hoge2: HogeClass2? = .init()
hoge2?.print(handler: { print("Hello, \($0)") })
hoge2 = nil
class HogeClass3 {
let text = "captured"
func print(handler: @escaping (String) -> Void) {
let txt = text
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
handler(txt)
}
}
deinit {
Swift.print("Bye, \(text)")
}
}
var hoge3: HogeClass3? = .init()
hoge3?.print(handler: { print("Hello, \($0)") })
hoge3 = nil
//
// Results
//
// Bye, weak
// Bye, captured
// Hello, <- weak but already released object.
// Hello, strong
// Bye, strong
// Hello, captured
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment