David Simon
David Simon

Reputation: 21

Using an IF query returns an error in Xcode

When I try to set an If query in Xcode (Swift & SwiftUI) in a view, I get the following error: Cannot invoke 'padding' with an argument list of type '(Double)'.

Once I comment out the If statement, the code works without problems. In the following code I have commented out the If statement.

What can I do to avoid the output of the error? The error is output at .padding(0.0)

    var body: some View {
    NavigationLink(destination: TransactionDetail(product: product)) {
        HStack {

            Text("X")
                .font(.largeTitle)
                .clipShape(Circle())
                .foregroundColor(.green)
                .overlay(Circle().stroke(Color.green, lineWidth: 1))
                .shadow(radius: 5)

            VStack(alignment: .leading) {
                HStack {
                   Text(product.name)
                        .font(.headline)
                        .foregroundColor(.black)
                }
                Text("21. Januar")
                    .font(.caption)
                    .foregroundColor(.black)
            }
            Spacer()
            Text("\(product.price),00 €")
                .font(.caption)
                .padding(2)
                /*
                if product.price > 0 {
                    .foregroundColor(.black)
                } else {
                    .foregroundColor(.black)
                }
                */
                .cornerRadius(5)
        }
        .padding(0.0)
    }
}

Upvotes: 0

Views: 60

Answers (2)

Martin R
Martin R

Reputation: 539775

This problem is unrelated to SwiftUI. The problem is that an if-statement does not have a value. In your example,

if product.price > 0 {
    .foregroundColor(.black)
} else {
    .foregroundColor(.black)
}

does not evaluate to a method call that can be applied to the Text view.

Here is a simple example would not compile either:

var uc = true
let string = "Hello World"
            if uc {
                .uppercased()
            } else {
                .lowercased()
            }

The simplest solution in your case would be

Text("\(product.price),00 €")
    .font(.caption)
    .padding(2)
    .foregroundColor(product.price > 0 ? .red : .green)
    .cornerRadius(5)

with a conditional expression as parameter of the foreground color.

Upvotes: 2

Chris
Chris

Reputation: 8091

you cannot use "normal" commands in SwiftUI - it is another concept. Normal statements you can have in functions, but not in the body. Maybe you should read some articles about the basics in SwiftUI.

Martin is right with his suggestion....

Upvotes: 0

Related Questions