[swift-evolution] What about a VBA style with Statement?

Brent Royal-Gordon brent at architechies.com
Thu Apr 14 20:44:03 CDT 2016


>> * The ability to name a closure parameter `self`, which would make bare method calls be directed to that parameter.
> 
> Could this would this tie into the weak-strong dance? And if so, how?

Actually, one of my motivations for wanting `self` parameters is the block-based undo registration API:

	func add(_ amount: Int) {
		value += amount
		undoManager.registerUndo(target: self) { self in subtract(amount) }
	}

Since undo managers reference targets weakly, this API encapsulates the weak-strong dance for you. But without `self` parameters, you end up having to invent a different name:

	func add(_ amount: Int) {
		value += amount
		undoManager.registerUndo(target: self) { target in target.subtract(amount) }
	}

And if you forget and accidentally use `self`, the block references `self` strongly, which could create a retain cycle. So `self` parameters would make this pattern—which is really the best way to handle a weak-strong dance—safer and cleaner, encouraging its use.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list