【问题标题】:How to unwrap an optional dictionary value in Swift 4+ in one step?如何在 Swift 4+ 中一步解开可选字典值?
【发布时间】:2018-11-23 04:24:44
【问题描述】:

鉴于下面的字典字典,解包 Int 的正确语法是什么?一步到位?

let dict:Dictionary<String, Dictionary<String, Int?>> = [
"parentKey" : [
    "firstKey" : 1,
    "secondKey" : nil]
]

let x = "someKey"
let y = "someOtherKey"
var foo = 0

if let goo = dict[x]?[y] { foo = goo } //<-- Error: cannot assign (Int?) to Int

if let goo = dict[x]?[y], let boo = goo { foo = boo } //<-- OK

在第一个 'if let' 中,goo 作为 Int 返回? - goo 然后需要像第二个'if let'一样解开......

一步完成的正确语法是什么?

【问题讨论】:

  • if let goo = dict[x]?[y] ?? NSNotFound { foo = goo } ?
  • 这会在两个键都有效时给出正确的结果(例如 x = "parentKey, y = "firstKey" 或 y = "secondKey"。但是,当 x 或 y 为一个不存在的键(例如 x = "someKey" 或 y = "someOtherKey")

标签: swift dictionary unwrap


【解决方案1】:

据我了解,您想强制解开双选项。有不同的方法。

let dbOpt = dict[x]?[y]

我最喜欢的:

if let goo = dbOpt ?? nil { foo = goo } 

使用flatMap

if let goo = dbOpt.flatMap{$0} { foo = goo } 

使用模式匹配:

if case let goo?? = dbOpt { foo = goo }

【讨论】:

    【解决方案2】:

    使用 nil colesecing 并提供默认值。安全解开字典值的唯一方法。

    if let goo = dict[x]?[y] ?? NSNotFound { foo = goo }  
    

    【讨论】:

      【解决方案3】:

      有很多方法可以做到这一点,但最简单的解决方案之一是:

      var foo = 0
      
      if let goo = dict[x]?[y]  as? Int{
          foo = goo
      }
      print(foo)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-11
        相关资源
        最近更新 更多