TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Ternary question...

Forums > SwiftUI

Why does this code fail with: Cannot infer contextual base in reference to member 'blue' on the let color line?

import SwiftUI

struct ContentView: View {
    @State private var iconSwitch: Bool = false

    var body: some View {
        VStack {

            let result = iconSwitch ? "globe" : "display"
            let color = iconSwitch ? .blue : .red
            let phrase = iconSwitch ? "Goodbye World!"  : "Hello World!"
            Image(systemName: result)
                .imageScale(.large)
                .foregroundColor(color)

            Text(phrase)
            Button("Switch") {
                iconSwitch.toggle()
            }.buttonStyle(.borderedProminent)
        }
        .padding()
    }
}

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

2      

It fails because the compiler doesn't know the type of .red and .blue.

Try let color: Color = ... or Color.red and Color.blue.

2      

While that code works. It better for SwiftUI to put ternary inside the views as it then know before time eg

struct ContentView: View {
    @State private var iconSwitch: Bool = false

    var body: some View {
        VStack {

//            let result = iconSwitch ? "globe" : "display"
//            let color: Color = iconSwitch ? .blue : .red
//            let phrase = iconSwitch ? "Goodbye World!"  : "Hello World!"

            Image(systemName: iconSwitch ? "globe" : "display")
                .imageScale(.large)
                .foregroundColor(iconSwitch ? .blue : .red)

            Text(iconSwitch ? "Goodbye World!"  : "Hello World!")
            Button("Switch") {
                iconSwitch.toggle()
            }.buttonStyle(.borderedProminent)
        }
        .padding()
    }
}

2      

Hmm, actually it was inside the view but not inside the modifier. I know about the problem about the reevaluating and redrawing. Does it make a difference in this case?

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.