Can we simplify let speedInt = try? await marker.viewModel.speed.values.first let speed: String = if let speedInt { "\(Int(speedInt)) km/h" } else { "-" }

Asked on 2025-11-13

1 search

To simplify the given Swift code snippet, you can use the new features introduced in Swift 6.2 that make handling optional values more concise. Here's a simplified version of your code:

let speedInt = try? await marker.viewModel.speed.values.first
let speed = speedInt.map { "\($0) km/h" } ?? "-"

This version uses the map function on the optional speedInt to transform it into a string if it has a value, and uses the nil-coalescing operator ?? to provide a default value of "-" if speedInt is nil.

For more information on concurrency and Swift, you might find the session Explore concurrency in SwiftUI helpful, as it covers concurrency optimizations and techniques in SwiftUI.