0

Swiftui dictionaries have the feature that the value returned by using key access is always of type "optional". For example, a dictionary that has type String keys and type String values is tricky to access because each returned value is of type optional.

An obvious need is to assign x=myDictionary[key] where you are trying to get the String of the dictionary "value" into the String variable x.

Well this is tricky because the String value is always returned as an Optional String, usually identified as type String?.

So how is it possible to convert the String?-type value returned by the dictionary access into a plain String-type that can be assigned to a plain String-type variable?

I guess the problem is that there is no way to know for sure that there exists a dictionary value for the key. The key used to access the dictionary could be anything so somehow you have to deal with that.

gary
  • 85
  • 7

1 Answers1

1

As described in @jnpdx answer to this SO question (How do you assign a String?-type object to a String-type variable?), there are at least three ways to convert a String? to a String:

import SwiftUI

var x: Double? = 6.0
var a = 2.0

if x != nil {
    a = x!
}

if let b = x {
    a = x!
}

a = x ?? 0.0

Two key concepts:

  1. Check the optional to see if it is nil
  2. if the optional is not equal to nil, then go ahead

In the first method above, "if x != nil" explicitly checks to make sure x is not nil be fore the closure is executed.

In the second method above, "if let a = b" will execute the closure as long as b is not equal to nil.

In the third method above, the "nil-coalescing" operator ?? is employed. If x=nil, then the default value after ?? is assigned to a.

The above code will run in a playground.

Besides the three methods above, there is at least one other method using "guard let" but I am uncertain of the syntax.

I believe that the three above methods also apply to variables other than String? and String.

gary
  • 85
  • 7