Building Type-Safe Metrics API in Swift Part II
Article Summary
Phil Niedertscheider from Sentry reveals how Swift's type system can catch metric API bugs before they compile. No more sending garbage data like memory addresses to production.
This is part II of Sentry's deep dive into building a type-safe Metrics API for their Swift SDK. The team tackled a critical problem: their logging API accepted Any types for attributes, allowing developers to accidentally pass invalid data that serialized into useless strings with memory addresses.
Key Takeaways
- Protocol-based union types replace Any, making invalid attribute values fail at compile time
- Custom types can adopt SentryAttributeValue to define their own metric representation
- Array handling required workarounds for Swift compiler limitations with generic constraints
- @unknown default enables forward compatibility when adding new enum cases in future releases
Sentry's new Swift Metrics API uses protocols and enums to guarantee type safety at compile time, eliminating an entire class of runtime data quality bugs.
About This Article
Sentry's initial Metrics API used type-erased Any for attribute values. This let developers pass unsupported types like custom classes, which would serialize to useless memory addresses such as $103d12130. The resulting data was non-deterministic and couldn't be queried.
Phil Niedertscheider's team built the SentryAttributeContent enum with associated values and the SentryAttributeValue protocol. This allows extensions on standard library types like String, Bool, Int, Double, and Float to automatically convert to supported attribute types.
The new API in sentry-cocoa v9.4.0 validates attribute values at compile time. This stops an entire class of runtime serialization bugs where invalid data used to ship to production without anyone noticing.