SwiftUI beginner question "cannot infer contextual base in reference to member"

New to SwifUI. Trying to attach property to an image or button to set a foregroundColor to green or red depending on the time of day. Also get the same error with .padding() and .border Assume cause is the same for all so limited example to one property.

It appears I cannot conditionally set a property because when I try I get "cannot infer contextual base in reference to member"

The function worked and made calls based on the passed argument. Problem appeared after conditionally trying to set foreground.Color

Simple experimental code:

@State private var phoneNumber = " "

Button { phoneNumber = "XXX-XXX-XXXX" callout(phonenum: phoneNumber) } label { Text("Using function to call") if oktime > nowtime { .foregroundColor.green } else { .foregroundColor.red } }

Please point me in the right direction. Googled the problem and became more confused.

Thanks in advance, D

//xcode 14

@State private var phoneNumber = " "

Button { phoneNumber = "--XXXX" callout(phonenum: phoneNumber) } label { Text("Using function to call") if oktime > nowtime { .foregroundColor.green } else { .foregroundColor.red

} }

Sorry even though I use indented code when submitted it makes it regular text

Your problem is in the if ... else statement.

The dot-notation .foregroundColor.green is used when you're accessing the properties of an object. In this case you want to get the green property of the foregroundColor, but you then want to assign it to something, and if you look at the code in one line you'll see the problem:

if <condition> .foregroundColor.green else .foregroundColor.red

You're trying to set the foregroundColor of the if statement.

you should do it this way:

struct ContentView: View {
	@State private var phoneNumber = " "

	let fgColor = (okTime > nowTime) ? Color.green : Color.red  // Use a ternary operator (`if <condition> ? true : false`) here to set the color before assigning it to the button's label

	var body: some View {
		Button {
			callout(phoneNumber)
		} label: {
			Text("Using function to call")
				.foregroundColor(fgColor)  // Use the variable you created above, and assign it to the foregroundColor property of the Text()
		}
	}
}

Thank you darkpaw for taking the time to help.

Your code worked flawlessly as expected.

One Note If another rookie stumbles on to this looking for answers I did have an issue of my own making. The code above kept crashing on the ternary. "Cannot use instance member 'nowtime' within property initializer; property initializers run before 'self' is available"

After some research yesterday I found out that structs do not initialize vars in order and only when needed. Once I moved the vars nowtime and oktime out of the struct under the import statements everything went smoothly.

Thanks again darkpaw!

SwiftUI beginner question "cannot infer contextual base in reference to member"
 
 
Q