1

I have declared following dictionary

var locations:Dictionary<String,String> = ["loc1":"Los Angeles","loc2":"San Francisco"];

then trying to simply assign it to a variable rather than a constant

var location:String = locations["loc1"];

but then the compiler is complaining about : Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?

If I change var location:String = locations["loc1"]; to var location:String? = locations["loc1"]; ,which means the String is optional, compiler error goes away.

but as you can see I haven't defined my dictionary to be optional e.g. Dictionary<String,String?>. So just wondering why does Swift convert my value type to be optional string(String?) behind the scene?

2 Answers 2

5

The code that pulls the value of the dictionary does not know whether or not locations["loc1"] will return a value - it could also return nil. Thus, it cannot be assigned to a non-optional String, as that would be a guarantee that the String is not nil, which is not the case.

However, if you want location as a non-optional String, you can initialize it, then use if let to unwrap the value from the dictionary:

var location : String = "Unknown"
if let value = locations["loc1"] {
     location = value
}

Slightly more verbose, but guarantees that location contains either a value or "Unknown" and cannot be nil.

Sign up to request clarification or add additional context in comments.

Comments

1

It's because your dictionary may not contain a value for that key so it returns a String optional just in case.

Comments

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.