user21666271
user21666271

Reputation:

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

Upvotes: 0

Views: 54

Answers (2)

Duncan C
Duncan C

Reputation: 131481

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

Upvotes: 1

DonMag
DonMag

Reputation: 77672

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

Upvotes: 0

Related Questions