How to return a value using ternary operators?

365 Views Asked by At
private var titleTextFieldStyle: TextFieldStyle  {
    get {
        isEditing ? RoundedBorderTextFieldStyle() : DefaultTextFieldStyle()
    }
}

What is the correct way to return a style using the ternary operator and compute concept. What I am doing wrong here?

2

There are 2 best solutions below

0
39fredy On

This is pseudo-code, but if I understand correctly you could do soothing like this:

let result = isEditing ? RoundedBorderTextFieldStyle() : DefaultTextFieldStyle()
return result 
0
Brett On

A year later and I can't find a nice way to do this either.

The issue is that RoundedBorderTextFieldStyle() and DefaultTextFieldStyle() aren't the same types. Actually they are the same types, so I don't know why this doesn't work.

I have built my own textStyle modifier for Text() and I used enums for the parameter to .textStyle(), you don't encounter these issues that way.

The only solution I have for TextField is to duplicate the code in the body:

var body: some View {
    Group {
        if isEditing {
            TextField("Editing", value: $text)
                .textStyle(RoundedBorderTextFieldStyle())
        }
        else {
            TextField("Not Editing", value: $text)
                .textStyle(DefaultTextFieldStyle())
        }
    }
}