Why 'if let' does not seem to unbox a value as before in Swift 3 in Xcode 8.3 beta?
Asked Answered
O

1

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!)")
    }
  }
}
Odericus answered 1/3, 2017 at 22:42 Comment(5)
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).Cannikin
But how would you differentiate a non existing value for a key than a key having a nil value? @CannikinWoolley
Unwrap it a second timeCannikin
Just change what you have to let title = item["label"] as? String and it'll work the way you're asking.Atbara
Related: How to unwrap double optionals? & Check if key exists in dictionary of type [Type:Type?] & Two (or more) optionals in Swift & Swift Optional Dictionary [String: String?] unwrapping errorCannikin
O
1

Ok then doing that for example solves the issue:

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

Odericus answered 1/3, 2017 at 23:12 Comment(1)
item["label"] ?? nil is another alternative, as shown in https://mcmap.net/q/190341/-how-to-unwrap-double-optionals/2976878Cannikin

© 2022 - 2024 — McMap. All rights reserved.