Quick Version Dictionary [String: String?]

So I have a basic setup

var preferenceSpecification = [String : String?]() preferenceSpecification["Key"] = "Some Key" preferenceSpecification["Some Key"] = nil preferenceSpecification["DefaultValue"] = "Some DefaultValue" print(preferenceSpecification) var defaultsToRegister = [String : String]() if let key = preferenceSpecification["Key"], let defaultValueKey = preferenceSpecification["DefaultValue"] { defaultsToRegister[key] = preferenceSpecification[defaultValueKey]! } 

But the error indicates where it requires me to force it to deploy to be as follows:

 defaultsToRegister[key!] = preferenceSpecification[defaultValueKey!]! 

Which doesn't make sense since keyValue and defaultValue are already deployed

0
dictionary swift
Aug 18 '16 at 19:39
source share
1 answer

When you retrieve a value from such a dictionary using an index

 [String: String?] 

you need to manage two levels of optional. The first one is because the index returns optional. Second, because the meaning of your dictionary is an optional string.

So when you write

 if let value = preferenceSpecification["someKey"] { } 

you get a value defined as an optional string.

Here is the code to fix that

 if let optionalKey = preferenceSpecification["Key"], key = optionalKey, optionalDefaultValueKey = preferenceSpecification["DefaultValue"], defaultValueKey = optionalDefaultValueKey, value = preferenceSpecification[defaultValueKey] { defaultsToRegister[key] = value } 

suggestions

  • You should avoid forced deployment. Instead, you managed to post 3 ! on one line!
  • You should also try to use a better name for your constants and variables.
+2
Aug 18 '16 at 19:58
source share



All Articles