【问题标题】:Can You Force a Dictionary To Return a Non Optional Or Assert?您可以强制字典返回非可选或断言吗?
【发布时间】:2020-01-17 19:32:24
【问题描述】:

有没有办法强制字典返回一个非可选值? , 如果它不存在就断言

var dic = Dictionary<String,String>()

dic["0"] = "Zero" 

let z = dic["0"] // is there a way that the 'z' variable will not be an optional (without doing an optional unwrapping, and so) , and if the value don't exists the program will assert 

这种事情可以通过字典的扩展来实现吗?

【问题讨论】:

  • 你的意思是this
  • 使用guard有什么问题?

标签: swift xcode dictionary


【解决方案1】:

您可以使用Nil-Coalescing Operator(a ?? b)

var dic = Dictionary<String,String>()

dic["0"] = "Zero" 

let z = dic["0"] ?? "Any Default String"

z 常量将是字符串类型。

一种更常见的处理可选项的方法是使用if letguard let

【讨论】:

    【解决方案2】:

    您可以在extension 中创建自己的自定义Dictionary subscript 函数。您需要添加一个标签以将其与普通的Dictionary 下标区分开来。

    示例:

    extension Dictionary {
        subscript(force key: Key) -> Value {
            if let value = self[key] {
                return value
            }
            fatalError("Forced key \(key) wasn't found in Dictionary")
        }
    }
    
    var dic = [String : String]()
    
    dic["0"] = "Zero"
    
    let z = dic[force: "0"]
    print(z)
    print(type(of: z))
    

    输出:

    Zero
    String
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      相关资源
      最近更新 更多