当我使用Any类型时,我对Swift如何检查nil感到困惑 这是一个例子:
let testA: Any? = nil
let testB: Any = testA as Any
let testC: Any? = testB
if testA != nil {
print(testA) // is not called as expected
}
if testB != nil {
print(testB) // prints "nil"
}
if testC != nil {
print(testC) // prints "Optional(nil)"
}
testA 按预期工作。变量为nil,因此条件为false。
testB 的效果并非如此。变量为nil,如打印调用所示。但条件testB != nil
的计算结果为true。为什么会这样?
testC 也让我感到困惑,因为它是testC = testB = testA。那么为什么它的行为应该与testA不同呢?
我如何才能将if条件if testB ...
和if testC ...
写成不正确
我正在寻找一种不需要我知道类型的解决方案,比如......
if let testB = testB as String
编辑:我正在使用Swift 4在Xcode 9.1 Playground文件中对此进行测试。
EDIT2:
关于我想解决的实际问题的一些信息。
我得到一个由JSON解析器创建的类型[String: Any?]
的字典。我想检查给定键的值是否为nil,但是当键存在且值为Optional(nil)时它不起作用。
示例:
var dict = [String: Any?]()
var string = "test"
var optionalString: String?
dict["key1"] = string
dict["key2"] = optionalString
if dict["key2"] != nil {
print(dict["key2"]) // should not be executed, but returns Optional(nil)
}
答案 0 :(得分:3)
在Swift中,nil实际上是一个具体值(类型为enum)。属于testB
类型的Any
持有值enum Optional
的{{1}},因此条件none
为真。
这解决了testB != nil
Any
如何能够保持零值的谜团。
针对您的实际问题,我在Storyboard(Xcode 9.2)中尝试了这段代码,它按预期工作。
testB
对于testB和testC,似乎= n检查nil应提供解决方案但是,因为二进制操作数不能与两个Any一起使用?操作数,我们不能使用==。
使用switch-case虽然可以给出正确的结果:
var dict = [String: Any]()
var string = "test"
var optionalString: String?
dict["key1"] = string
dict["key2"] = optionalString
if let value = dict["key2"] {
print(value) // doesn't get executed
}
<强> O / P 强>:
价值是没有
价值是没有