Why += works in a swift playground but not in the swift app?

Why you can use += in a swift playground but not in the swift app? So – where is the problem? If I write += in the app – there comes the error ‚Type ‚()‘ cannot conform to ‚View‘‘

App:

import SwiftUI

struct ContentView: View {
    var body: some View {
        var addUp = 0
        addUp += 2 //error
    }
}

Playground:

var addUp = 0
addUp += 2 //adds 2

But there is no problem in the playground. Do you know why? And how I can use it in the app?

Thank you!

>Solution :

You have declared the var addup = 0 inside of the VIEW

move the addup variable declaration outside the scope of var body: some view {}

you need to actually return a view like below. This returns a ScrollView

   var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
            ///code in here
            }
        }
    }

Leave a Reply