强制 Swift Dictionary 返回非可选或断言?

问题描述 投票:0回答:2

有没有办法强制 Swift

Dictionary
返回非可选值?如果键的值不存在,则应该断言。

var dic = Dictionary<String,String>()

dic["0"] = "Zero" 

let z = dic["0"] // Want this to be non-optional, or assert.

我该如何编写这个变量,以便

z
变量将成为 非可选(不执行可选的展开)?如果该值不存在,程序应断言,类似于
Array
下标访问。

这可以通过

Dictionary
的扩展实现吗?

swift xcode dictionary
2个回答
1
投票

您可以在

Dictionary
中创建自己的自定义
subscript
extension
函数。您需要添加一个标签以将其与正常的
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

0
投票

您可以使用 无合并运算符

(a ?? b)

var dic = Dictionary<String,String>()

dic["0"] = "Zero" 

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

z 常量将为 String 类型。

处理可选值的更常见方法是使用

if let
guard let

© www.soinside.com 2019 - 2024. All rights reserved.