I'm familiar with the if let ..
pattern for unwrapping optionals and use this frequently to check for nil
, however when dealing with dictionaries in Swift the pattern seems to break down. Can someone explain why the following does not work in Swift 4? ... The following snippet is Playground Ready!™
import UIKit
let test: Any? = nil
if let _ = test {
print("This works as expected and does not print")
}
//let d1: [String: Any] = ["foo": "fooval", "bar": NSNull()]
let d2: [String: Any?] = ["foo": "fooval", "bar": NSNull(), "flim": nil]
if let _ = d2["flim"] {
print("I don't expect this to print but it does")
}
Ultimately I want to extend Dictionary
so there is a null check for JSON parsing/encoding which can handle both missing values (where nil
is returned from the key AFAIK) and JSON null values which I guess return NSNull
(at least that what is required when encoding to get a JSON null value). Here is what I have so far
extension Dictionary where Key == String {
func isNullOrEmpty(key: String) -> Bool {
// Value is NSNull instance
if let _ = self[key] as? NSNull {
return true
}
// Test if value is optional and null
if let _ = self[key] {
return false
}
// Test if key/value is missing altogether
if self[key] == nil {
return true
}
return false
}
}