Yesterday a coworker of mine and I were trying get a red border to appear around an input field if the input text is not valid. I had this working with a simple Ternary Operator that was setting the border opacity to 1 if the state was invalid and 0 if not, but we refactored the enum that has the different cases to manage state so that they have associated values to allow passing in a message which would make the call site cleaner. In doing so we discovered that using something like case .invalid = validationState ? 1.0 : 0.0
was not allowed and I'd like to know why that is. Is the syntax wrong or does Swift just not allow this? And if so, was this intentional, and why?
Here's the enum:
public enum ValidationState: Equatable {
case none
case valid(message: String, textColor: Color?)
case invalid(message: String, textColor: Color?)
case checking(message: String, textColor: Color?)
case notChecked(message: String, textColor: Color?)
public var message: String {
switch self {
case .none:
return ""
case .valid(message: let message, _):
return message
case .invalid(message: let message, _):
return message
case .checking(message: let message, _):
return message
case .notChecked(message: let message, _):
return message
}
}
public var textColor: Color? {
switch self {
case .none:
return nil
case .valid(_, textColor: let textColor):
return textColor ?? .green
case .invalid(_, textColor: let textColor):
return textColor ?? .red
case .checking(_, textColor: let textColor):
return textColor ?? Color(.standardTextColor)
case .notChecked(_, textColor: let textColor):
return textColor ?? Color(.standardTextColor)
}
}
public var isInvalid: Bool {
switch self {
case .invalid:
return true
default:
return false
}
}
}
Here's where I was trying to use a Ternary Operator, but had to make a computed property instead (opacityForInvalidBorder
):
// This is what it looks like now:
.opacity(opacityForInvalidBorder)
// This is the property that computes the opacity
private var opacityForInvalidBorder: Double {
if case .invalid = validationState {
return 1.0
} else {
return 0.0
}
}
My coworker and I were saying it would've been great to be able to say something like:
.opactity(case .invalid = validationState ? 1.0 : 0.0)
Any clarification on this is appreciated. Thanks for taking the time to read this. I hope I was clear with my question and the problem we were trying to solve. If not, please let me know so I can explain further.
Cheers!