Search code examples
swiftswiftuicasting

Cast Int? to a String in a Text Component


Is there a simple way of casting an optional Int to a String in SwiftUI and displaying it?

Ideally without having to check for nil while also having a default Int of 0?

var body: some View {
    HStack {
        workout.duration != nil ? Text(String(workout.duration ?? 0)) : nil
    }
}

Solution

  • some examples, first unwrapping Int with default option

     Text("\(workDuration ?? 0)")
    

    Second case not to show a default text, and not to draw object Text (paddings, modifiers associates)

     if let workDuration != nil { Text("\(workDuration ?? 0)") }
    

    Third more elegant as suggested by George, same as second option

     if let workDuration = workDuration { Text("\(workDuration)") }
    

    Four, following Rob Napier's comment, unwrapping your model

      struct Workout {
        var duration: Int?
        var durationDescription : String {
             "\(duration ?? 0)"
        }
      }
      
      struct ContentView: View {
        let workout = Workout(duration: 33) //sample
    
        var body: some View {
           Text("\(workout.durationDescription)")
        }
     }