Search code examples
iosswifterror-handlingviewaddition

How to sum up in a view in swift?


How to sum up in a view in swift? This function is one of the simplest things you can do, but it don‘t work. Is it really so hard to sum up two numbers? Many games have a score or something like that. How they do that - maybe you know it. I tried this (below) but there is an error in line 4.

struct ContentView: View{
    var body: some View{
        func sumup(a: Int, b: Int) -> Int{
            return a + b // error
        }
        Text(String(sumup(a: 3, b: 8)))
    }
}


Solution

  • Problem

    In the above code the function sumup is inside body

    Learning the basics

    My personal opinion is that you learn the basics of SwiftUI, it would help you understand things better.

    You could start by watching Introduction to SwiftUI

    Corrected Code

    struct ContentView: View{
        var body: some View{
            Text(String(sumup(a: 3, b: 8)))
        }
        
        func sumup(a: Int, b: Int) -> Int{
            return a + b
        }
    }