swift-atoms/swift-tagged
Use this package when two values share a representation but must not be mixed up, such as a customer identifier and an order identifier that are both strings: wrap the value in Tagged<Tag, Underlying>, where Tag is a phantom type that names the domain. Start from Tagged. To
Laws
- The tag exists only in the type. A
Taggedvalue has the same memory layout as itsUnderlying, encodes and decodes as the bare underlying value, and itsdescriptionandidare the underlying ones, so two values with different tags but the same underlying value print and identify alike. When decoding, the receiving type alone decides the domain. init(_unchecked:)and theCarrier.Protocolinitializer attach the tag without checking anything. Any invariant must be enforced byUnderlyingbefore tagging; a failing underlying initializer means noTaggedvalue is made.- Equality, hashing and ordering are those of
Underlying, so sorting follows the underlying order and sets deduplicate by underlying value. On a tie,Tagged.maxandTagged.minreturn their first argument. mapkeeps the tag and is a functor: mapping the identity returns an equal value, and mappinggthenfequals mappingf(g(x)). A throwing transform's error propagates and no value is produced.retagkeeps the underlying value unchanged: retagging there and back returns an equal value, retagging through several tags equals retagging directly, andmapandretagcommute.- Nesting does not flatten: a
Taggedwhose underlying value is anotherTaggedreports the innerTaggedas itsUnderlyingand its own tag as itsDomain. Each layer is unwrapped explicitly. - Literal and string-interpolation initializers build the underlying value from the literal and tag it, giving the same value as
init(_unchecked:).
Package Metadata
Repository: swift-atoms/swift-tagged
Default branch: main
README: README.md