I'm confused about how Swift checks for nil when I'm using the Any type.
Here's an example:
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 works as expected. The variable is nil, so the condition is false.
testB works not as expecte. The variable is nil, as shown by the print call. But the condition testB != nil
evaluates to true. Why is this the case?
testC confuses me as well, since it is testC = testB = testA. So why should it behave differently than testA?
How would I need to write the if conditions if testB ...
and if testC ...
to not be true.
I'm looking for a solution that doesn't require me to know the type, like ...
if let testB = testB as String
Edit: I'm testing this with Swift 4 in an Xcode 9.1 Playground file.
Edit2:
Some information about the actual problem I want to solve.
I'm getting a dictionary of type [String: Any?]
that is created by a JSON parser. I want to check if the value for a given key is nil, but it doesn't work, when the key exists and the value is Optional(nil).
Example:
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)
}