首页 > 解决方案 > 在 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;
}

标签: swift

解决方案


您的语法非常非常客观-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
}

推荐阅读