Last active
June 11, 2021 06:48
-
-
Save MrSmart00/99dc39edc87bdb442dc0d46f0b687a62 to your computer and use it in GitHub Desktop.
Escaping内のキャプチャ挙動確認用 via Playground
This file contains 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
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