'Getting error : Expected expression in list of expressions

Can i not use switch to check for a variable and implement a view based on the variable's value. I tried using if else as well but still getting the same error. Do I have to create a method and return a view for the same and use it here?

struct AppThemeButton: View {

    var action: (() -> Swift.Void)?
    var buttonType: ThemeButtonType = .bordered

    var body: some View {
        Button {
            // button action
            if let act = action {
                act()
            }
        
        } label: {
            Text("+ \(TextStrings.addAProject.localized())")
                .frame(maxWidth: .infinity, maxHeight: .infinity, 
alignment: .center)
                .background(
                    switch self.buttonType {
                    case .bordered:
                        Color.green
                    case .colored:
                        Color.red
                    }
                )
                .frame(height: 60, alignment: .center)
                .padding([.leading, .trailing])
        }
    }
}

enum ThemeButtonType {
    case bordered
    case colored
}

Code with error



Solution 1:[1]

You're using this modifier https://developer.apple.com/documentation/swiftui/view/background(_:alignment:), it requires a View as parameter not a function or closure.

The modifier is deprecated since iOS 15. If your app is targeted iOS 15 and above, you can use this new modifier https://developer.apple.com/documentation/swiftui/view/background(alignment:content:)

In case of below iOS 15, you should wrap your label by your switcher

enum ThemeButtonStyle: ButtonStyle {
    case filled
    case bordered
    
    func makeBody(configuration: Configuration) -> some View {
        switch self {
        case .filled:
            configuration.label
                .foregroundColor(.white)
                .padding()
                .background(Capsule().fill(.red))
        case .bordered:
            configuration.label
                .foregroundColor(.black)
                .padding()
                .background(Capsule().stroke(.black))
        }
    }
}

struct AppThemeButton: View {
    let style: ThemeButtonStyle
    var body: some View {
        Button {
            print("Touched")
        } label: {
            Text("Touch Me")
        }.buttonStyle(style)
    }
}

struct ThemeButtonStyle_Previews: PreviewProvider {
    static var previews: some View {
        VStack {
            AppThemeButton(style: .filled)
            AppThemeButton(style: .bordered)
        }
    }
}

Result

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quang Hà