0

Unlike before, I was surprised to see that 'title' is now an optional (the compiler now generates the waning : String interpolation produces a debug description for an optional value; did you mean to make this explicit?).

How it comes the 'if let title =' expression does no unbox it anymore? What should I do to unbox in the if?

// Go thru all publication where the tag has been found
for item in items {
  if let item = item as? [String: String?], let title = item["label"] {
    i += 1
    if let rawSummary = item["libSousTheme"] {
      print("\(i)) Tag [\(foundTag)] z[\(foundZTag)] in « \(title) »")
    }
    else {
      print("\(i)) Tag [\(foundTag)] z[\(foundZTag)] in « \(title) » (no summary!)")
    }
  }
}
Stéphane de Luca
  • 12,745
  • 9
  • 57
  • 95
  • 1
    `title` should have been an optional prior to Swift 3.1, as you're casting to `[String: String?]`, and a dictionary's subscript uses `nil` to indicate the lack of a value for a key (so you get a double wrapped optional for `item["label"]`). Generally, you never want to have a dictionary with an optional `Value` type – just use a non-optional `Value` type and use `nil` to indicate the lack of a value for key (i.e cast to `as? [String: String]` instead). – Hamish Mar 01 '17 at 22:47
  • But how would you differentiate a non existing value for a key than a key having a nil value? @Hamish – Stéphane de Luca Mar 01 '17 at 22:49
  • 1
    Unwrap it a second time – Hamish Mar 01 '17 at 22:49
  • 2
    Just change what you have to `let title = item["label"] as? String` and it'll work the way you're asking. – creeperspeak Mar 01 '17 at 22:49
  • 1
    Related: [How to unwrap double optionals?](http://stackoverflow.com/q/33049246/2976878) & [Check if key exists in dictionary of type \[Type:Type?\]](http://stackoverflow.com/q/29299727/2976878) & [Two (or more) optionals in Swift](http://stackoverflow.com/q/27225232/2976878) & [Swift Optional Dictionary \[String: String?\] unwrapping error](http://stackoverflow.com/q/39026275/2976878) – Hamish Mar 01 '17 at 22:54

1 Answers1

1

Ok then doing that for example solves the issue:

if let item = item as? [String: String?], let title = item["label"] ?? nil { /* … */ }

Stéphane de Luca
  • 12,745
  • 9
  • 57
  • 95
  • 2
    `item["label"] ?? nil` is another alternative, as shown in http://stackoverflow.com/q/33049246/2976878 – Hamish Mar 01 '17 at 23:26