Created
May 3, 2017 16:46
-
-
Save curtclifton/d537752629284b61aa846313845dfe66 to your computer and use it in GitHub Desktop.
Nerd snipery
This file contains hidden or 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 | |
hooks.numberOfSectionsIn = disown(function: Frame.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 | |
} | |
private func disown<In, Out>(function: @escaping ((Frame) -> (In) -> Out)) -> ((In) -> Out) { | |
let result: ((In) -> Out) = { [unowned self] arg in | |
let selflessFunc = function(self) | |
return selflessFunc(arg) | |
} | |
return result | |
} | |
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