Last active
May 3, 2017 15:21
-
-
Save jsorge/fe51cbbc2450366fc43e895e1a091bdc to your computer and use it in GitHub Desktop.
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
//: Playground - noun: a place where people can play | |
import UIKit | |
class VC { | |
var dataSource: DataSource? | |
func viewDidLoad() { | |
let items = dataSource?.numberOfItemsIn(section: 9) ?? -1 | |
print("There are \(items) items") | |
} | |
deinit { | |
print("deinit on the VC") | |
} | |
} | |
class DataSource { | |
struct Hooks { | |
var numberOfSectionsIn: ((_: Int) -> Int?)? | |
} | |
var hooks: Hooks? | |
func numberOfItemsIn(section: Int) -> Int { | |
guard hooks?.numberOfSectionsIn?(section) == nil else { return hooks!.numberOfSectionsIn!(section)! } | |
return 99 | |
} | |
deinit { | |
hooks = nil | |
print("deinit on the data source") | |
} | |
} | |
class Frame { | |
var dataSource: DataSource? = DataSource() | |
let itemCount = 100 | |
init() { | |
var hooks = DataSource.Hooks() | |
// Right here I want to capture an unowned self | |
hooks.numberOfSectionsIn = numberOfSectionIn | |
// But if I pass in a closure with an unowned self, there's no problem | |
// hooks.numberOfSectionsIn = { [unowned self] (section) -> Int? in | |
// return self.itemCount | |
// } | |
dataSource?.hooks = hooks | |
} | |
func numberOfSectionIn(_ section: Int) -> Int? { | |
// The DataSource hook now has a strong reference to Frame | |
return itemCount | |
} | |
deinit { | |
dataSource = nil | |
print("deinit on the frame") | |
} | |
} | |
var frame: Frame? = Frame() | |
var vc: VC? = VC() | |
vc?.dataSource = frame!.dataSource | |
vc?.viewDidLoad() | |
vc = nil | |
frame = nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment