Skip to content

Instantly share code, notes, and snippets.

@jechol
Last active January 12, 2017 04:22
Show Gist options
  • Save jechol/5fb5bf84f9ca25d97e0fe073396c47bb to your computer and use it in GitHub Desktop.
Save jechol/5fb5bf84f9ca25d97e0fe073396c47bb to your computer and use it in GitHub Desktop.
Swift nested closure reference capture test
import Foundation
typealias VoidFunc = () -> ()
class Person {
var name: String!
init(_ name: String) {
self.name = name
}
deinit {
print("deinit for \(name!)")
}
func strong() -> VoidFunc {
return {
print("inside \(self.name)")
}
}
func weak() -> VoidFunc {
return { [weak self] in
print("inside \(self?.name)")
}
}
func unowned() -> VoidFunc {
return { [unowned self] in
print("inside \(self.name)")
}
}
func strongThenStrong() -> () -> VoidFunc {
return {
return {
print("inside \(self.name)")
}
}
}
func unownedThenStrong() -> () -> VoidFunc {
return { [unowned self] in
return {
print("inside \(self.name)")
}
}
}
func strongThenUnowned() -> () -> VoidFunc {
return {
return { [unowned self] in
print("inside \(self.name)")
}
}
}
}
var strong = Person("strong").strong()
var weak = Person("weak").weak()
var unowned = Person("unowned").unowned()
var strongThenStrong = Person("strongThenStrong").strongThenStrong()()
var unownedThenStrong = Person("unownedThenStrong").unownedThenStrong()()
var strongThenUnowned = Person("strongThenUnowned").strongThenUnowned()()
print("-- end of program --")
deinit for weak
deinit for unowned
deinit for unownedThenStrong
deinit for strongThenUnowned
-- end of program --
@w4-hojin
Copy link

var strong = Person("strong").strong()
var weak = Person("weak").weak()
// deinit for weak
var unowned = Person("unowned").unowned()
// deinit for unowned
var strongThenStrong = Person("strongThenStrong").strongThenStrong()()
var unownedThenStrong = Person("unownedThenStrong").unownedThenStrong()()
// deinit for unownedThenStrong
var strongThenUnowned = Person("strongThenUnowned").strongThenUnowned()()
// deinit for strongThenUnowned

이렇게 써주시면 더 보기 좋을꺼같아요!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment