Swift5.4中可选的误报

我有一个 Dictionary 扩展,它在 Xcode 12.5 和 Swift 5.4 发布之前一直运行良好。问题是在 Swift5.4 中似乎发生了变化,这使得可选的可选返回作为误报。在某种程度上它确实有意义,但是现在我的扩展失败了。

考虑以下示例代码:

let dictionary: [String: Any] = ["foo": "bar"]

if let foo = dictionary["foo"] as? String? {
    debugPrint("Foo exists")
}

if let bar = dictionary["bar"] as? String? {
    debugPrint("bar exists")
}

在 Swift 5.4 之前,这将导致以下结果:

"Foo exists"

但是现在在 Swift 5.4 中,我得到以下结果:

"Foo exists"
"bar exists"

这是因为即使字典被定义为[String: Any],anString?符合类型Any,因此nil符合any,因此 if 情况会触发,因为 nil 是 any。

对我来说,这给我正在使用的 require 函数带来了一个问题,如果泛型类型设置为 optional 就会触发。我的扩展:

"Foo exists"

我的问题:有没有办法检查是否T是可选类型?如果是这样,我可以调整我的代码来检查泛型类型是可选的,确保prop不是零。

回答

您的示例代码也打印"bar exists"在 Xcode 12.4 中。

无论如何,请尝试使用以下实现require

func require<T>(_ name: String) throws -> T {
    guard let index = self.index(forKey: name) else {
        throw DictionaryExtractionError.missingProperty(name)
    }
    guard let t = self[index].value as? T else {
        throw DictionaryExtractionError.casting(name)
    }
    return t
}


以上是Swift5.4中可选的误报的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>