swiftswiftuiinitialization

I cannot run the code when I declare a color variable in SwiftUI


I am trying to learn the initializer in SwiftUI. Everything goes fine when I try to run the following code, as you see on the uploaded picture.

enter image description here

When I try to start to build the initializer modifying the code, as you see by declaring a color variable

import SwiftUI

struct ContentView: View {
    //Creation of variables outside the body
    
    var body: some View {
        let backgroundColor: Color
        
        VStack(spacing: 15){
            Text("5")
                .font(.largeTitle)
                .foregroundColor(.white)
                .underline()
            Text("Apples")
                .font(.headline)
                .foregroundColor(.white)
        }
        .frame(width: 150, height: 150)
        .background(backgroundColor)
        .cornerRadius(10.0)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(backgroundColor: .red)
    }
}

I obtain the following errors:

  1. Local variable 'backgroundColor' requires an explicit initializer to be used with result builder 'ViewBuilder'

  2. Argument passed to call that takes no arguments

  3. Cannot infer contextual base in reference to member 'red'

I am using the version 14.2 of Xcode. The first error suggested me to return in the steps of the uploaded picture, things that I want to avoid because I cannot run the code using init or enum. How these errors can be corrected? Any help would be appreciated.


Solution

  • The problem is that you declare backgroundColor in the wrong location. It needs to be a property of the ContentView struct, not inside the body code.

    Simply move the line.

    struct ContentView: View {
        //Creation of variables outside the body
        let backgroundColor: Color
        
        var body: some View {
            VStack(spacing: 15){
                Text("5")
                    .font(.largeTitle)
                    .foregroundColor(.white)
                    .underline()
                Text("Apples")
                    .font(.headline)
                    .foregroundColor(.white)
            }
            .frame(width: 150, height: 150)
            .background(backgroundColor)
            .cornerRadius(10.0)
        }
    }
    

    Now the code you posted will compile and work.

    However, if there are any references to ContentView in your app that look like this:

    ContentView()
    

    then they will need to be updated to provide a background color just as you do inside ContentView_Previews:

    ContentView(backgroundColor: .blue) // pick a color