64619

Swift Optional Dictionary [String: String?] unwrapping error

Question:

So here 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 points out where it demands that I force unwrap this, to be like this:

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

Which doesn't make sense, because <em>keyValue</em> and <em>defaultValue</em> already are unwrapped

Answer1:

When you extract a value from a dictionary like this using subscript

[String: String?]

you need to manage 2 levels of optional. The first one because the subscript returns an optional. The second one because the value of you dictionary is an optional String.

So when you write

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

you get value defined as an optional String.

Here's the code to fix that

if let optionalKey = preferenceSpecification["Key"], key = optionalKey, optionalDefaultValueKey = preferenceSpecification["DefaultValue"], defaultValueKey = optionalDefaultValueKey, value = preferenceSpecification[defaultValueKey] { defaultsToRegister[key] = value } <h2>Suggestions</h2> <ol><li>You should avoid force unwrapping as much as possible. Instead you managed to put 3 ! on a single line!</li> <li>You should also try to use better name for your constants and variables. </li> </ol>

Recommend

  • UWP with Desktop Bridge package build automation with MSbuild
  • How to evaluate var Array in nodejs, at client side?
  • Same intrinsic parameter for same camera?
  • How to insert into Sqlite with optional parameters using Swift 3
  • Canonical example of ConfigurationProperty
  • Building Preference screen in code depending on another setting
  • Symfony2 - Call to undefined method getDoctrine() when overriding FOSUserBundle's ProfileContro
  • NUnit/Moq: I have mocked a class but real contructor is executed, why?
  • How to create Photoshop Stamp filter analog in any pixel shading language?
  • React/Javascript--FileReader//adding image
  • control margin properties depending on another control margin properties in wpf
  • How to remove the title bar from PreferenceCategory in PreferenceActivity
  • how to map json to java object having a different structure using jackson mixins
  • CKEditor on focus remove default value
  • Difference between optional values in swift?
  • Dynamic cast to generic type in Java
  • phase unwrap issue (the unwrapping of the phases is not correcly)?
  • pulling specific record(s) that match only a set of values across multiple rows
  • C# 6 bool and new null check with ? what to return back
  • Swift where condition to check if a property is implemented
  • Outlook 365 add-in only appears in Outlook 2013 client
  • Parse JSON value as Enum in Rust
  • onFocus and onBlur
  • Can't figure out a function to return a reference to a given type stored in RefCell
  • How do I add a UIAlertController in app delegate (obj-c)
  • R h2o.glm - issue with max_active_predictors
  • How to use the resource module to measure the running time of a function?
  • IE6 changes DOCTYPE to a bad one
  • How to draw a line dynamically in android [duplicate]
  • Google Places API - Find a company's CID and LRD
  • Doctrine/Symfony entity generator and generating entity from one table
  • Android Studio Can't Find tools.jar
  • Default parameter as generic type
  • How to detect interior vertices in groups of 2d polygons? (E.g. ZIP Codes to determine a territory)
  • Converting a WriteableBitmap image ToArray in UWP
  • How reduce the height of an mschart by breaking up the y-axis
  • Traverse Array and Display in markup
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Linking SubReports Without LinkChild/LinkMaster
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass