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
Critical Insight
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.