swift - 在 Swift 中从 NSDictionary 获取密钥时断言失败
问题描述
我想了解下面的函数如何有时会生成一个 Swift "_assertionFailure" in line: if let s = dict![key] as?细绳
我想如果 dict![key] 没有找到,一个 nil 会返回,所以 if let 会得到一个 nil 值并且条件会失败,没有错误,没有断言。我哪里错了?
func getDictKey(_ dict: NSDictionary?, key: String) -> String?
{
var value: String?;
if (dict != nil && !key.isEmpty)
{
if let s = dict![key] as? String {
value = s;
}
}
return value;
}
解决方案
您的语法非常非常客观-c-ish。
在 Swift 中,您可以简单地编写
func getDictKey(_ dict: NSDictionary?, key: String) -> String?
{
return dict?[key] as? String
}
它包含除空字符串检查之外的所有检查。如果字典是 ,则后面的问号会dict
中止链nil
。
你不应该NSDictionary
在 Swift 中使用,而是更有意义的命名
func getValue(from dict: [String:Any]?, forKey key: String) -> String?
{
return dict?[key] as? String
}
推荐阅读
- python - 基于 python 的 Dockerfile 抛出 locale.Error: unsupported locale setting
- firebase - AMP 列表 Firebase INVALID_ARGUMENT __amp_source_origin
- node.js - 无法使用 imap 连接到 Gmail
- html - List-style-type: none 不适用于删除与导航栏中项目相关的项目符号(点)
- d3.js - 在已绘制的元素上拖动事件
- vba - 如何在访问中编辑使用“更新后”选项创建的宏
- r - 闪亮未检测到输出中的输入
- html - CSS :hover 抽搐
- simple-injector - 使用非泛型接口装饰类,其中装饰器依赖于接口,而不是类
- haskell - 在 Haskell 中为命令式语言编写解释器