gary
gary

Reputation: 85

How do you assign a String?-type object to a String-type variable?

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?

Upvotes: 0

Views: 477

Answers (2)

gary
gary

Reputation: 85

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".

Upvotes: 0

jnpdx
jnpdx

Reputation: 52416

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.

Upvotes: 1

Related Questions