Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
71: NumberFormatter and MeasurementFormatter
I've reviewed a lot of PRs over the years, and there is one pattern that always makes me sigh: the "hardcoded format" trap. It usually looks something like this: "\(amount) kg" or String(format: "%.2f", price). It seems harmless when you're testing on your own simulator in your own timezone, but it's a ticking time bomb for your international users.
The Myth: "String Interpolation is Enough for Formatting"
The common misconception is that numbers are universal. You might think that because 1,234.56 is clear to you, it's clear to everyone. It isn't. In many European countries, the comma and the period are swapped (1.234,56), and some locales use a non-breaking space as a thousands separator.
// The "naive" way that fails in Germany or France
let balance = 1234.56
let displayString = "Your balance is $\(balance)"
// Output: "Your balance is $1234.56" (No matter where the user lives)
If you ship this, you're telling your users that your app doesn't speak their language. Beyond just the decimal point, hardcoding symbols like "$" or "kg" is a mistake because currency symbols and unit placements vary wildly across the globe.
The Fix: Letting NumberFormatter Handle the Locale
This is where NumberFormatter comes in. Instead of you deciding where the comma goes, you tell Swift the intent of the number, and it asks the system how to render it for the current user's locale.
let formatter = NumberFormatter()
formatter.numberStyle = .currency // Handles symbol and placement automatically
formatter.locale = Locale(identifier: "de_DE") // Forcing German for this example
if let formattedPrice = formatter.string(from: 1234.56 as NSNumber) {
print(formattedPrice) // "1.234,56 €"
}
Notice how the Euro symbol moved to the end and the separators swapped? I didn't write a single line of logic to handle that. By using .numberStyle = .currency or .decimal, you're delegating the complexity to the OS, which is exactly what you want.
Stop Manually Multiplying Units with MeasurementFormatter
Now, measurements are a whole different beast. I see developers doing math like distanceInKm * 0.621371 to get miles. Please, stop doing that. Not only is it prone to rounding errors, but it's a nightmare to maintain as you add more units.
Swift provides Measurement and MeasurementFormatter to handle this. You define the value and the unit, and the formatter handles the conversion and the localized string representation in one go.
let distance = Measurement(value: 10, unit: UnitLength.kilometers)
let formatter = MeasurementFormatter()
formatter.unitOptions = .naturalScale // Automatically chooses km vs m based on magnitude
// If the user is in the US, this automatically converts to miles
print(formatter.string(from: distance))
// Output (US): "6.21 miles"
// Output (France): "10 km"
The .naturalScale option is a personal favorite of mine. It ensures that if a distance is 1,500 meters, it might show up as "1.5 km" instead of a giant string of meters, depending on the locale's preferences. It makes your UI feel polished and professional without you having to write a dozen if/else statements.
📋 Practical Task
Building a Localized Health Metric Dashboard
You are building a health app that tracks a user's daily water intake and running distance. Currently, the code is hardcoded for US English, and it looks amateur. Your task is to refactor the following code to use NumberFormatter and MeasurementFormatter so that it adapts to the user's locale.
// CURRENT BROKEN CODE
let waterIntake = 2500.5 // Milliliters
let runDistance = 5.25 // Kilometers
// TODO: Refactor these prints to use proper Formatters
print("Water: \(waterIntake) ml")
print("Distance: \(runDistance) km")
Requirements:
- Create a
NumberFormatterto display the water intake as a decimal number with no more than 1 fraction digit. - Create a
MeasurementFormatterto display the run distance. Ensure it uses.naturalScaleso that the unit is appropriate for the locale. - Initialize the
Measurementobject usingUnitLength.kilometers. - Test your output by temporarily setting
formatter.locale = Locale(identifier: "en_US")and then"fr_FR"to verify the units and separators change automatically.
There are no comments for now.