iosswiftswiftuidoublecurrency-formatting

Swift binary operator can not be applied into formatted function


I am trying to add sum of the to values and converts to currency with hard coded string using formatted function. but I am having following errors.

Binary operator '+' cannot be applied to operands of type 'Double' and 'String'

I have tried formatted function with passing currency signal values and working fine but when I tried to use + operator to add two values I got above error .

Here is the line that rise the error ..

if isOn2 {
Text("\(order.productTotal + fee.formatted(.currency(code: "GBP")))")
        .bold()
       }
Here is the code ..

struct OrderView: View {
@State private var isOn1 = false
@State private var isOn2 = false

    var body: some View {

                 HStack {
                      Text("Grand total is :")
                            .bold()
                        Spacer()
                        if isOn2 {
                            Text("\(order.productTotal + fee.formatted(.currency(code: "GBP")))")
                                .bold()
                        } else {
                            Text("\(order.productTotal.formatted(.currency(code: "GBP")))")
                                .bold()
                        }
                    }
                    .padding(5)
}

Here is the screenshot..

enter image description here


Solution

  • If you want to add order.productTotal to fee and display the sum as a formatted string, use

    Text("\((order.productTotal + fee).formatted(.currency(code: "GBP")))")
        .bold()
    

    (Add the two values together, and then format the sum as currency.)