TSAO is an implementation of type-safe associated objects in Swift. Objective-C associated objects are useful, but they are also untyped; every associated object is only known to be id at compile-time and clients must either test the class at runtime or rely on it being the expected type.
Swift allows us to do better. We can associate the value type with the key used to reference the value, and this lets us provide a strongly-typed value at compile-time with no runtime overhead¹. What’s more, it allows us to store value types as associated objects, not just object types, by transparently boxing the value (although this involves a heap allocation). We can also invert the normal way associated objects work and present this type-safe adaptor using the semantics of a global map from AnyObject to ValueType.
It’s also possible to specify the association policy. For all values, atomic/nonatomic retain is supported. For class values, assign is also supported. And for NSCopying values, atomic/nonatomic copy is supported.
To properly use this library, the AssocMap values you create should be static or global values (they should live for the lifetime of the program). You aren’t required to follow this rule, but any AssocMaps you discard will end up leaking an object (this is the only way to ensure safety without a runtime penalty).

Leave a Reply
You must be logged in to post a comment.