Home > Net >  Swift binary operator can not be applied into formatted function
Swift binary operator can not be applied into formatted function

Time:11-05

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

CodePudding user response:

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.)

CodePudding user response:

You need to convert order.productTotal into a string, using \() and also convert the result of fee.formatted(.currency(code: "GBP")) into a string.

Change:

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

to:

Text("\(order.productTotal) \(fee.formatted(.currency(code: "GBP")))")
  • Related