0

I would like to assign the value element of a dictionary to a String variable.

In swiftUI, all value elements in dictionaries are returned as String? type.

When a String? type is assigned to a String variable, the String variable displays in the swiftUI app as Optional("theStringIamTryingToDisplay").

How do I get rid of the "Optional" in the app display?

gary
  • 85
  • 7

2 Answers2

1

You'll have to first make sure that the variable doesn't in fact contain nil. You can do that in a number of ways -- might be good to read:

One way is by optional binding:

if let myVariable = myDictionary["key"] {
  Text(myVariable)
}

Another is to provide an default value:

Text("My result: \(myDictionary["key"] ?? "default value")

There are other possibilities, but these, plus the links above, should get you started.

jnpdx
  • 45,847
  • 6
  • 64
  • 94
0

Thank you very much, jnpdx:)

Ok, after much studying of optionals, it seems that one solution is:

for String variables "x" and "y", dictionary myDictionary=["a":"aaa", "b":"bbb", "c":"ccc"], the assignment of a swiftUI dictionary value, which is ALWAYS an optional, to a string variable using the default as part of the assignment statement will suppress the "Optional" display. It looks like:

y = "(myDictionary[x] ?? "anyDefaultDummyTextHere")"

I should have gotten that from @jnpdx's second answer but the Text() object confused me as I was focused on the "y =" assignment statement.

Seems that since y is always preventing from being assigned "nil" by the default thingy "??", then y no longer displays as "Optional".

gary
  • 85
  • 7