Help with calc app pls

can someone simpliy my calc app??? :weary_face::weary_face::weary_face:

import SwiftUI

enum calculatorButton: String {

**case** one, two, three, four, five, six, seven, eight, nine, zero, equal, plus, minus, multiply, division

**case** clear, negative, percent, decimal



**var** title: String {

    **switch** **self** {

    **case** .one: **return** "1"

    **case** .two: **return** "2"

    **case** .three: **return** "3"

    **case** .four: **return** "4"

    **case** .five: **return** "5"

    **case** .six: **return** "6"

    **case** .seven: **return** "7"

    **case** .eight: **return** "8"

    **case** .nine: **return** "9"

    **case** .zero: **return** "0"

    **case** .equal: **return** "="

    **case** .plus: **return** "+"

    **case** .minus: **return** "-"

    **case** .multiply: **return** "x"

    **case** .division: **return** "/"

    **case** .clear: **return** "AC"

    **case** .negative: **return** "+/-"

    **case** .percent: **return** "%"

    **case** .decimal: **return** "."

    }

}

**var** buttonColor: Color {

    **switch** **self** {

    **case** .plus, .minus, .multiply, .division, .equal:

        **return** .accentColor

    **case** .clear, .negative, .percent:

        **return** Color.gray

    **default**:

        **return** Color(UIColor(red: 55/255, green: 55/255, blue: 55/255, alpha: 1))

    }

}

}

enum Operation {

**case** add, subtract, multiply, divide, none

}

struct CalculatorView: View {

@State **var** value = "0"

@State **var** currentOperation: Operation = .none

@State **var** runningNumber = 0



**let** buttons: \[\[calculatorButton\]\] = \[

    \[.clear, .negative, .percent, .division\],

    \[.seven, .eight, .nine, .multiply\],

    \[.four, .five, .six, .minus\],

    \[.one, .two, .three, .plus\],

    \[.zero, .decimal, .equal\]

\]



**var** body: **some** View {

    ZStack {

        VStack {

            HStack {

                Spacer()

                    Text(value)

                        .shadow(color: .accentColor, radius: 10)

                        .fontWidth(.expanded)

                        .fontWeight(.regular)

                        .font(.system(size: 80))

                        .foregroundColor(.primary)

            }

            .padding()

            

            ForEach(buttons, id: \\.**self**) { row **in**

                HStack(spacing: 0) {

                    ForEach(row, id: \\.**self**) { item **in**

                        Button{

                            **self**.didTap(button: item)

                        } label: {

                            **if** **#available**(iOS 26.0, \*) {

                                Text(item.title)

                                    .buttonStyle(.glass)

                                    .fontWidth(.expanded)

                                    .ignoresSafeArea()

                                    .scaledToFit()

                                    .font(.system(size: 32))

                                    .frame(width: **self**.buttonWidth(item: item), height: **self**.buttonHeight())

                                    .background(item.buttonColor)

                                    .hoverEffect(.lift)

                                    .shadow(color: .accentColor, radius: 10)

                                    .opacity(0.5)

                                    .foregroundColor(.white)

                                    .ignoresSafeArea()

                                    .cornerRadius(**self**.buttonWidth(item: item) / 999)

                            } **else** {

                                // Fallback on earlier versions

                            }

                        }

                    }

                }

                .padding(.bottom, -8)

            }

        }

    }

    .padding()

    .ignoresSafeArea()

    .background(MeshGradient(

        width: 3,

        height: 3,

        points: \[

            \[0.0, 0.0\], \[0.5, 0.0\], \[1.0, 0.0\],

            \[0.0, 0.5\], \[0.9, 0.3\], \[1.0, 0.5\],

            \[0.0, 1.0\], \[0.5, 1.0\], \[1.0, 1.0\]

        \],

        colors: \[

            .clear,.clear,.clear,

            .clear, .clear, .clear,

            .accentColor, .accentColor, .accentColor

        \]

    ).ignoresSafeArea())

}

**func** didTap(button: calculatorButton) {

    **switch** button {

    **case** .plus, .minus, .multiply, .division, .equal:

        **if** button == .plus {

            **self**.currentOperation = .add

            **self**.runningNumber = Int(**self**.value) ?? 0

        } **else** **if** button == .minus {

            **self**.currentOperation = .subtract

            **self**.runningNumber = Int(**self**.value) ?? 0

        } **else** **if** button == .multiply {

            **self**.currentOperation = .multiply

            **self**.runningNumber = Int(**self**.value) ?? 0

        } **else** **if** button == .division {

            **self**.currentOperation = .divide

            **self**.runningNumber = Int(**self**.value) ?? 0

        } **else** **if** button == .equal {

            **let** runningValue = **self**.runningNumber

            **let** currentValue = Int(**self**.value) ?? 0

            **switch** **self**.currentOperation {

            **case** .add:

                **self**.value = "\\(runningValue + currentValue)"

            **case** .subtract:

                **self**.value = "\\(runningValue - currentValue)"

            **case** .multiply:

                **self**.value = "\\(runningValue \* currentValue)"

            **case** .divide:

                **self**.value = "\\(runningValue / currentValue)"

            **case** .none:

                **break**

            }

        }

        **if** button != .equal {

            **self**.value = "0"

        }

    **case** .clear:

        **self**.value = "0"

    **case**.decimal, .negative, .percent:

        **break**

    **default**:

        **let** number = button.title

        **if** **self**.value == "0" {

            value = number

        }**else** {

            **self**.value = "\\(**self**.value)\\(number)"

        }

    }

}

**func** buttonWidth(item: calculatorButton) -> CGFloat {

    **if** item == .zero {

        **return** (UIScreen.main.bounds.width - (4 \* 12)) / 4 \* 2

    }

    **return** (UIScreen.main.bounds.width - (4 \* 12)) / 4

}

**func** buttonHeight() -> CGFloat {

    **return** (UIScreen.main.bounds.width - (4 \* 12)) / 9

}

}

preview {

CalculatorView()

    .preferredColorScheme(.light)

}

sorry if its like that.

Please edit your post to surround your code listing with triple backquotes to format it like code, and paste it again without preserving formatting so that the keywords are not bold, etc.

Also, please give us more detail about what it is exactly you’d like to simplify here. There are many ways to simplify code!

1 Like

Please pay attention to what @Slava_Pestov is saying. :slight_smile:

If you paste your code between a pair of triple backtick characters (```) like this:

```
Paste Code Here
```

The code will be not only easier to view but also easier to copy and paste.

For example:

import SwiftUI

enum calculatorButton: String {
   case one, two, three, four, five, six, seven, eight, nine, zero, equal, plus, minus, multiply, division
   case clear, negative, percent, decimal

   var title: String {
      switch self {
      case .one:   return "1"
      case .two:   return "2"
      case .three: return "3"
...

With the "swift" keyword after the first three backticks.

1 Like

I need it to be more simplified.

Also, updated post here:

import SwiftUI

enum calculatorButton: String {
    case one, two, three, four, five, six, seven, eight, nine, zero, equal, plus, minus, multiply, division
    case clear, negative, percent, decimal
    
    var title: String {
        switch self {
        case .one: return "1"
        case .two: return "2"
        case .three: return "3"
        case .four: return "4"
        case .five: return "5"
        case .six: return "6"
        case .seven: return "7"
        case .eight: return "8"
        case .nine: return "9"
        case .zero: return "0"
        case .equal: return "="
        case .plus: return "+"
        case .minus: return "-"
        case .multiply: return "x"
        case .division: return "/"
        case .clear: return "AC"
        case .negative: return "+/-"
        case .percent: return "%"
        case .decimal: return "."
        }
    }
    var buttonColor: Color {
        switch self {
        case .plus, .minus, .multiply, .division, .equal:
            return .accentColor
        case .clear, .negative, .percent:
            return Color.gray
        default:
            return Color(UIColor(red: 55/255, green: 55/255, blue: 55/255, alpha: 1))
        }
    }
}
enum Operation {
    case add, subtract, multiply, divide, none
}


struct CalculatorView: View {
    @State var value = "0"
    @State var currentOperation: Operation = .none
    @State var runningNumber = 0
    
    let buttons: [[calculatorButton]] = [
        [.clear, .negative, .percent, .division],
        [.seven, .eight, .nine, .multiply],
        [.four, .five, .six, .minus],
        [.one, .two, .three, .plus],
        [.zero, .decimal, .equal]
    ]
    
    var body: some View {
        ZStack {
            VStack {
                HStack {
                    Spacer()
                        Text(value)
                            .shadow(color: .accentColor, radius: 10)
                            .fontWidth(.expanded)
                            .fontWeight(.regular)
                            .font(.system(size: 80))
                            .foregroundColor(.primary)
                }
                .padding()
                
                ForEach(buttons, id: \.self) { row in 
                    HStack(spacing: 0) {
                        ForEach(row, id: \.self) { item in
                            Button{
                                self.didTap(button: item)
                            } label: {
                                if #available(iOS 26.0, *) {
                                    Text(item.title)
                                        .buttonStyle(.glass)
                                        .fontWidth(.expanded)
                                        .ignoresSafeArea()
                                        .scaledToFit()
                                        .font(.system(size: 32))
                                        .frame(width: self.buttonWidth(item: item), height: self.buttonHeight())
                                        .background(item.buttonColor)
                                        .hoverEffect(.lift)
                                        .shadow(color: .accentColor, radius: 10)
                                        .opacity(0.5)
                                        .foregroundColor(.white)
                                        .ignoresSafeArea()
                                        .cornerRadius(self.buttonWidth(item: item) / 999)
                                } else {
                                    // Fallback on earlier versions
                                }
                            }
                        }
                    }  
                    .padding(.bottom, -8)
                }
            }
        }
        .padding()
        .ignoresSafeArea()
        .background(MeshGradient(
            width: 3,
            height: 3,
            points: [
                [0.0, 0.0], [0.5, 0.0], [1.0, 0.0],
                [0.0, 0.5], [0.9, 0.3], [1.0, 0.5],
                [0.0, 1.0], [0.5, 1.0], [1.0, 1.0]
            ],
            colors: [
                .clear,.clear,.clear,
                .clear, .clear, .clear,
                .accentColor, .accentColor, .accentColor
            ]
        ).ignoresSafeArea())
    }
    func didTap(button: calculatorButton) {
        switch button {
        case .plus, .minus, .multiply, .division, .equal:
            if button == .plus {
                self.currentOperation = .add
                self.runningNumber = Int(self.value) ?? 0
            } else if button == .minus {
                self.currentOperation = .subtract
                self.runningNumber = Int(self.value) ?? 0
            } else if button == .multiply {
                self.currentOperation = .multiply
                self.runningNumber = Int(self.value) ?? 0
            } else if button == .division {
                self.currentOperation = .divide
                self.runningNumber = Int(self.value) ?? 0
            } else if button == .equal {
                let runningValue = self.runningNumber
                let currentValue = Int(self.value) ?? 0
                switch self.currentOperation {
                case .add:
                    self.value = "\(runningValue + currentValue)"
                case .subtract:
                    self.value = "\(runningValue - currentValue)"
                case .multiply:
                    self.value = "\(runningValue * currentValue)"
                case .divide:
                    self.value = "\(runningValue / currentValue)"
                case .none:
                    break
                }
            }
            if button != .equal {
                self.value = "0"
            }
        case .clear:
            self.value = "0"
        case.decimal, .negative, .percent:
            break
        default:
            let number = button.title
            if self.value == "0" {
                value = number
            }else {
                self.value = "\(self.value)\(number)"
            }
        }
    }
    func buttonWidth(item: calculatorButton) -> CGFloat {
        if item == .zero {
            return (UIScreen.main.bounds.width - (4 * 12)) / 4 * 2
        }
        return (UIScreen.main.bounds.width - (4 * 12)) / 4
    }
    func buttonHeight() -> CGFloat {
        return (UIScreen.main.bounds.width - (4 * 12)) / 9
    }
}

#Preview {
    CalculatorView()
        .preferredColorScheme(.light)
}



Sorry if it’s long. I’m just love coding.

Oh, thanks :+1:

You can model a NumberInputKeypad or something to avoid switch your number case to get title String. Just use number.description. And use OOP or POP for InputKeypad so that you can store an array in your data model.

struct NumberInputKeypad: InputKeypad {
    var number: Int

    var title: String { number.description }
}

eg.

Better to handle the number overflows and division by zero. :slight_smile:

See the Overflow Operators section in the Advanced Operators chapter TSPL Book.

See also: Performing Calculations with Overflow in Int documentation.

Performing Calculations with Overflow

These methods return the result of an operation, and a flag indicating whether the operation overflowed the bounds of the type.

func addingReportingOverflow(Int) -> (partialValue: Int, overflow: Bool)

Returns the sum of this value and the given value, along with a Boolean value indicating whether overflow occurred in the operation.

func subtractingReportingOverflow(Int) -> (partialValue: Int, overflow: Bool)

Returns the difference obtained by subtracting the given value from this value, along with a Boolean value indicating whether overflow occurred in the operation.

func multipliedReportingOverflow(by: Int) -> (partialValue: Int, overflow: Bool)

Returns the product of this value and the given value, along with a Boolean value indicating whether overflow occurred in the operation.

func dividedReportingOverflow(by: Int) -> (partialValue: Int, overflow: Bool)

Returns the quotient obtained by dividing this value by the given value, along with a Boolean value indicating whether overflow occurred in the operation.

func remainderReportingOverflow(dividingBy: Int) -> (partialValue: Int, overflow: Bool)

Returns the remainder after dividing this value by the given value, along with a Boolean value indicating whether overflow occurred during division.