1

I'm trying to use a Text label to output a string based on a UserDefault setting for what the translation they prefer:

Text(settings.translation? tangoArray[self.id].romaji : tangoArray[self.id].hiragana)

Is there any reason why the above line of code doesn't work, and what small modification do I need to make?

3
  • is the setting connected in a view hierarchy Commented Jan 25, 2020 at 3:56
  • it's in my ContentView. class UserSettings: ObservableObject { @Published var translation = UserDefaults.standard.integer(forKey: "Translation") } Commented Jan 25, 2020 at 4:02
  • please provide a simple example. Commented Jan 25, 2020 at 4:05

1 Answer 1

2

If the translation is defined as (and hopefully changed somewhere as well)

class UserSettings: ObservableObject {
    @Published var translation = UserDefaults.standard.integer(forKey: "Translation")
}

... then it has Int type, but in Text you must have Bool, so it should be like

Text(settings.translation == _romaji_int_code_ ? 
    tangoArray[self.id].romaji : tangoArray[self.id].hiragana)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that works! If I were to expand to this a third option "both (romaji and hiragana)", how would I do it?
Not sure I understood what do you mean... how are you going to store 'both' translation values under one key? and what would that act for?
Say in my database I have a third column that is a concatenation of the first two. I want to offer this option to my users if they want to see both romaji and hiragana. So I'm almost writing a switch statement inside the Text, but that doesn't seem elegant does it?
It depend... on ui design, on requirement to extendability... it is possible to do with if, with switch, extract it into separated view builder... in short, depends... elegant is not always a criteria, as for me... but that's different question. ))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.