[swift-evolution] associated objects

Brent Royal-Gordon brent at architechies.com
Fri Sep 30 01:13:14 CDT 2016


> On Sep 28, 2016, at 9:27 AM, Robert Widmann via swift-evolution <swift-evolution at swift.org> wrote:
> 
> To make this kind of pattern type safe you would, for example, need to keep track metatype pointers too and use the dynamic cast machinery to check the type on retrieval.

Actually, a somewhat different (DispatchSpecificKey-style) design makes type safety pretty easy:

	import Cocoa
	
	let myValue = AssociatedValue(.strong, ofType: String.self, on: NSView.self)
	
	let view = NSView()
	myValue[view] = "Hello, world!"
	myValue[view]

Implementation here: <https://gist.github.com/brentdax/75bfd619379fea53d8ca8afaa16d95bb>

Nevertheless, I don't think this should be shipped in Swift; associated objects are as esoteric as they come.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list