Xcode 12.5.1中调用Measurement<UnitEnergy>的formatted方法报错:类型'Measurement<UnitEnergy>'没有成员'formatted'
Hey there! I’ve run into this exact issue before when working with older Xcode versions—let’s break down why it’s happening and how to fix it.
The Root Cause
The formatted() method for Measurement types is a relatively new API, introduced in watchOS 8 / iOS 15. But Xcode 12.5.1 is tied to the watchOS 7 SDK (since it’s paired with iOS 14), which doesn’t include this method yet. That’s why your code is throwing that error—your environment doesn’t recognize the newer syntax from the tutorial.
Two Ways to Fix This
1. Use the Older (But Compatible) MeasurementFormatter
If you need to stick with Xcode 12.5.1 (for example, to support older watchOS devices), rewrite your code using MeasurementFormatter instead. This is the legacy way to format measurements that works with watchOS 7 and earlier:
// Create your measurement let calorieMeasurement = Measurement(value: 47, unit: UnitEnergy.kilocalories) // Set up the formatter to match the tutorial's desired style let formatter = MeasurementFormatter() formatter.unitOptions = .abbreviated // Shortens "kilocalories" to "kcal" formatter.numberFormatter.maximumFractionDigits = 0 // No decimal places formatter.unitStyle = .short // Matches the workout usage context // Pass the formatted string to Text Text(formatter.string(from: calorieMeasurement))
2. Upgrade Xcode (Recommended for Future Projects)
If you don’t need to support watchOS 7 or older, upgrading to Xcode 13 or later will let you use the exact code from the tutorial. Xcode 13 and above include the watchOS 8 SDK, which supports the formatted() method natively. Just keep in mind:
- Xcode 13 requires macOS Big Sur 11.3 or newer, so make sure your Mac meets the system requirements first.
- Upgrading will also give you access to newer Swift features and watchOS APIs, which is great for learning the latest tech stack.
内容的提问来源于stack exchange,提问作者Epicminetime

